The Apple logo is a registered trademark of Apple Computer, Inc. Use of the “keyboard”
Apple logo (Option-Shift-K) for commercial purposes without the prior written consent of
Apple may constitute trademark infringement and unfair compe-tition in violation of federal and state laws.
Apple Computer, Inc.
20525 Mariani Avenue
Cupertino, CA 95014-6299
408-996-1010
Apple, the Apple logo, APDA, AppleLink, AppleShare,
AppleTalk, Apple IIGS, A/UX, EtherTalk, HyperCard, Hyper-Talk, ImageWriter, LaserWriter, LocalTalk, Mac, Macintosh, MPW, MultiFinder, SANE, and TokenTalk are registered trade-marks of Apple Computer, Inc.
Apple Desktop Bus, Balloon Help, Finder, KanjiTalk, Moof, QuickDraw, ResEdit, TrueType, and Zhong-Wen Talk are trade-marks of Apple Computer, Inc.
Helvetica and Times are
registered trademarks of
Linotype Company.
ITC Zapf Dingbats is a registered trademark of International Typeface Corporation.
MacPaint is a registered trade-mark of Claris Corporation.
NuBus is a trademark of Texas
Instruments.
PostScript is a registered trade-mark, and Illustrator is a
trademark, of Adobe Systems
Incorporated.
Sony is a registered trademark of Sony Corporation.
UNIX is a registered trademark of UNIX System Laboratories, Inc.
Simultaneously published in the United States and Canada.
Limited Warranty on Media and Replacement
Even though Apple has
reviewed this manual, APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS MANUAL, ITS QUALITY, ACCURACY, MERCHANT-ABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. AS A RESULT, THIS
MANUAL IS SOLD “AS
IS,” AND YOU, THE PUR-CHASER, ARE ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND
ACCURACY.
IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT,
INDIRECT, SPECIAL,
INCIDENTAL, OR CONSE-QUENTIAL DAMAGES
RESULTING FROM ANY
DEFECT OR INACCURACY IN THIS MANUAL, even if advised of the possibility of such damages.
THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL
OTHERS, ORAL OR
WRITTEN, EXPRESS OR
IMPLIED. No Apple dealer, agent, or employee is
authorized to make any
modification, extension, or
addition to this warranty.
Some states do not allow the exclusion or limitation of
implied warranties or liability for incidental or consequential damages, so the above
limitation or exclusion may not apply to you. This warranty gives you specific legal rights, and you may also have other rights which vary from state to state.
The Edition Manager
About the Edition Manager1-3
Publishers, Subscribers, and Editions1-4
Using The Edition Manager1-12
Receiving Apple Events From the Edition Manager1-12
Creating the Section Record and Alias Record1-15
Saving a Document Containing Sections1-19
Opening and Closing a Document Containing Sections1-22
Reading and Writing a Section1-25
Formats in an Edition1-25
Opening an Edition1-27
Format Marks1-27
Reading and Writing Edition Data1-28
Closing an Edition1-28
Creating a Publisher1-29
Creating the Edition Container1-32
Opening an Edition Container to Write Data1-35
Creating a Subscriber1-37
Opening an Edition Container to Read Data1-41
Choosing Which Edition Format to Read1-41
Using Publisher and Subscriber Options1-43
Publishing a New Edition While Saving or Manually1-47
Subscribing to an Edition Automatically or Manually1-48
Canceling Sections Within Documents1-48
Locating a Publisher Through a Subscriber1-49
Renaming a Document Containing Sections1-50
Displaying Publisher and Subscriber Borders1-50
Text Borders1-54
Spreadsheet Borders1-55
Object-Oriented Graphics Borders1-55
Bitmapped Graphics Borders1-57
Duplicating Publishers and Subscribers1-57
Modifying a Subscriber1-59
Relocating an Edition1-59
Customizing Dialog Boxes1-59
Subscribing To Non-Edition Files1-62
Getting the Current Edition Opener1-63
Setting an Edition Opener1-63
Calling an Edition Opener Procedure1-63
Opening and Closing Editions1-67
Listing Files That Can Be Subscribed To1-67
Reading From and Writing to Files1-67
Calling a Format I/O Procedure1-68
Reference to the Edition Manager1-69
Routines1-70
Initializing the Edition Manager1-70
Creating and Registering a Section1-71
Creating and Deleting an Edition Container1-76
Setting and Locating a Format Mark1-77
Reading in Edition Data1-79
Writing out Edition Data1-81
Closing an Edition After Reading or Writing1-83
Displaying Dialog Boxes1-85
Locating a Publisher and Edition From a Subscriber1-92
Edition Container Formats1-94
Reading and Writing Non-Edition Files1-95
Summary of the Edition Manager1-98
1The Edition Manager
This chapter describes how you can use the Edition Manager to allow your users to share and automatically update data from numerous documents and applications.
The Edition Manager is available only in system software version 7.0. It can be used by many different applications located on a single disk or throughout a network of Macintosh<Superscript\>\xa8 computers. To test for the existence of the Edition Manager, use the Gestalt function, described in the Compatibility Guidelines chapter of this volume.
Read the information in this chapter if you want your application’s documents to share and automatically update data, or if you want to share and automatically update data with documents created by other applications that support the Edition Manager.
For example, a user might want to capture sales figures and totals from within a spreadsheet and then include this information in a word-processing document that summarizes sales for a given month. The Edition Manager establishes a connection between these two documents. When a user modifies the spreadsheet, the information in the word-processing document can be automatically updated to contain the latest changes. To accomplish this, both the spreadsheet application and the word-processing application must support the features of the Edition Manager.
To use this chapter, you should be familiar with sending and receiving high-level events, described in the Events Manager chapter of this volume. Your application must also support Apple<Superscript\>\xa8 events to receive Apple events from the Edition Manager. See the Apple Event Manager chapter in this volume for detailed information.
About the Edition Manager
The Edition Manager provides you with the ability to
n capture data within a document and integrate it into another document
n modify information in a document and automatically update any document that shares its data
n share information between applications on the same computer or across a network of Macintosh computers
Building the capabilities of the Edition Manager into your program is similar to building cut-and-paste features into your program. Text, graphics, spreadsheet cells, database reports—any data that you can select, you can make accessible to other applications that support the Edition Manager.
This chapter first defines the main elements of the Edition Manager and then discusses how to save, open, read, and write a document that shares data. In addition, this chapter describes how to
n make data accessible to other applications
n integrate data into numerous documents
n set update options
n implement borders
n modify shared data
n customize dialog boxes
This chapter also describes an advanced feature that allows applications to share data directly from a file.
Publishers, Subscribers, and Editions
A section is a portion of a document that shares its contents with other documents. The Edition Manager supports two types of sections: publishers and subscribers. A publisher is a section within a document that makes its data available to other documents or applications. A subscriber is a section within a document that obtains its data from other documents or applications.
Your application writes a copy of the data in each publisher to a separate file called an edition container. The actual data that is written to the edition container is referred to as the edition. Your application obtains the data for each subscriber by reading data from the edition container. Note that throughout this chapter, the term edition refers to the edition container and the data it contains.
You publish data when you want to make it available to other documents and applications. When data is published, it is stored in an edition container. You subscribe to data that a publisher makes available by reading an edition from its container.
Section and edition container are programmatic terms. You should not use them in your application or your documentation. Use publishers, subscribers, and editions. You should also refrain from using other terms such as publication or subscription to describe the dynamic sharing of information provided by the Edition Manager. Use the terms publish and subscribe to describe the Edition Manager features.<36pt\>\x12 <8bat\>u
Each edition has an icon that is visible from the Finder. Figure 1-1 shows the default
edition icon.
The default edition icon
The name that the user specifies for the edition is located next to the edition icon. To create customized edition icons, see the Finder Interface chapter in this volume for detailed information. Figure 1-2 illustrates a document containing a single publisher, its corresponding edition, and a subscriber to the edition in another document.
A publisher, an edition, and a subscriber
Note that the publisher and subscriber borders illustrated in Figure 1-2 may appear slightly different from the borders you see on screen. Figure 1-6 shows a screen-captured image of the publisher and subscriber borders that appear on screen.
Data always flows in one direction, from publisher to edition to subscriber. Documents that contain publishers and subscribers do not have to be open at the same time to share data. Whenever the user saves a document that contains a publisher, the edition changes to reflect the current data from the publisher. All subscribers update their contents from the edition. Any number of subscribers can subscribe to a single edition.
To create a publisher within a document, a user selects an area of the document to share and chooses Create Publisher from the Edit menu (illustrated later in this chapter). Figure 1-3 shows the dialog box that your application should display when the user chooses Create Publisher.
The publisher dialog box
Your application provides a thumbnail sketch of the edition data that the Edition Manager displays in the preview area of the publisher dialog box. Your preview of the edition in this dialog box should provide a visual cue about the type of information that the user has selected to publish.
A preview area also appears in the subscriber dialog box (see Figure 1-4). Your preview for an edition in this dialog box should provide a visual cue about the type of information the edition contains. For example, it should allow users to distinguish between text information and spreadsheet arrays.
The publisher dialog box uses the extended interface of the standard file dialog box that accompanies system software version 7.0. The user navigates through the contents of the disk using the mouse or keyboard.
A user can modify a publisher within a document just like any other portion of a document. As a default, each time a user saves a document containing a publisher, your application should automatically write the publisher’s data to the edition. You also need to provide the user with the choice of sending new publisher data to an edition manually (that is, only at the user’s specific request). You should provide these options by using the publisher options dialog box described later in “Using Publisher and Subscriber Options.”
For example, one user may choose to automatically update an edition each time a document is saved. This update mode is useful for a user who creates a publisher within a spreadsheet application that records stock information. Each time the user updates the stock information and saves the spreadsheet, a new edition automatically becomes available to subscribers.
Another user may choose to update an edition only upon request. This update mode might be useful for a user who creates a publisher within a word-processing application for a quarterly sales report. The user incrementally updates the sales report throughout the entire quarter, but does not want this information to be available to subscribers until the end of the quarter. Only at the end of each quarter does the user specifically request to update the edition and make it available to any subscribers.
To create a subscriber within a document, the user places the insertion point and chooses Subscribe To from the Edit menu. Figure 1-4 shows the dialog box that your application should display when the user chooses Subscribe To.
The subscriber dialog box
The subscriber dialog box also uses the extended interface of the standard file dialog box introduced with system software version 7.0. Initially, the dialog box should highlight the name of the last edition published or subscribed to. This allows a user to create a publisher and immediately subscribe to its edition.
A subscriber receives its data from a single edition. By default, your application should automatically update a document containing a subscriber whenever a new edition is available. You also need to provide the user with the choice of receiving the latest edition manually (that is, only when the user specifically requests it). You can provide these options by using the subscriber options dialog box described later in “Using Publisher and Subscriber Options.”
For example, one user may choose to automatically receive new editions as they become available. This update mode is useful for a user who subscribes to information from an edition that consists of daily sales figures. This user automatically acquires each version of the sales information as it becomes available.
Another user may choose to receive a new edition only upon request. This update mode is useful for a user who creates a subscriber to an edition that consists of graphics data (such as a company logo). The user may require only periodic versions of the logo and not need frequent updates. In this case, your application should only update the subscriber with a new edition when the user specifically requests it.
A user can select, cut, copy, or paste an entire subscriber. Although the contents of the subscriber as a whole can be modified, a user cannot edit portions of a subscriber. For example, a user can underline or italicize the entire subscriber text, but cannot delete a sentence or rotate a single graphical object. This restriction protects the user from losing changes to a subscriber when a new edition arrives. Remember that, as a default, new editions should automatically update a subscriber. Any changes that a user made to the subscriber text would have to be reapplied by the user when the new edition arrives. See “Modifying a Subscriber” later in this chapter for further information.
A single document can contain any number or combination of publishers and subscribers. Figure 1-5 shows an example of a document that contains two publishers and one subscriber (and their corresponding editions). Remember that data always flows in one direction, from publisher to edition to subscriber. The “Concert flyer” document contains a publisher that is subscribed to by the “Benefit concert” document. The “Concert flyer” document also subscribes to a portion of the “Pianos & palm trees” document. In addition, the “Concert flyer” document as a whole is subscribed to by the “Sample flyer” document.
A document and its corresponding editions
You should distinguish each selected publisher and subscriber within a document with a border. Display a publisher border as 3 pixels wide with 50 percent gray lines, and display a subscriber border as 3 pixels wide with 75 percent gray lines. A rectangle of one white pixel should separate the data from the border itself. Borders should be drawn outside the contents of publishers and subscribers so that data is not obscured. See Figure 1-6 for an illustration of the borders as they appear on screen. See “Displaying Publisher and Subscriber Borders” later in this chapter for detailed information on how to implement borders for specific applications.
Figure 1-6 shows a document containing a publisher and a document containing a subscriber, with borders displayed for each.
Borders for publishers and subscribers should behave like the borders of 'PICT' graphics within a word-processing document. Your application should display a border whenever the user clicks within the content area of a publisher or a subscriber. Your application should hide the border whenever the user clicks outside the content area. See “Displaying Publisher and Subscriber Borders” later in this chapter for detailed information on how to implement borders for specific applications.
Publisher and subscriber borders
You also need to support the standard Edition Manager menu commands in the Edit menu. These menu items include
n Create Publisher…
n Subscribe To…
n Publisher/Subscriber Options…
n Show/Hide Borders (optional)
n Stop All Editions (optional)
Use a dotted line to separate the Edition Manager menu commands from the standard Edit menu commands Cut, Copy, and Paste. Figure 1-7 shows the standard Edition Manager menu commands.
Edition Manager commands in the Edit menu
The Subscriber Options menu command should toggle with the Publisher Options menu command. When a user selects a subscriber, the Subscriber Options menu command should appear in the menu and when a user selects a publisher, the Publisher Options menu command should appear in the menu. In addition, you may support a Show Borders menu command that toggles with Hide Borders to display or hide all publishers and subscriber borders within documents. You may also support a Stop All Editions menu command to provide a method for temporarily suspending all update activity in a document. When the user chooses this command, you should place a checkmark next to it. You should also stop all publishers from sending data to editions and all subscribers from receiving new editions. When the user chooses this command again, remove the checkmark and update any subscribers that are set up to receive new editions automatically.
If you find that you need all of the available space in the Edit menu for your application’s commands, you may create a hierarchical menu for the Edition Manager menu commands. If you choose to implement this structure, you should allow users to access the Edition Manager menu commands through a Publishing menu command in the Edit menu. Because this menu structure is not as accessible to users, you should implement it only if you have no other alternative.
Figure 1-8 shows the Edition Manager menu commands in a hierarchical menu structure.
Edition Manager commands under the Publishing menu command
For each publisher or subscriber within an open document, you must have a section record and an alias record. The section record contains a time stamp that records the version of the data that resides in the section. The section record also identifies the section as either a publisher or subscriber, and it establishes a unique identity for each publisher or subscriber. The section record does not contain the data within the section. The alias record is a reference to the edition container from the document that contains the corresponding publisher or subscriber section.
There are special options associated with publishers and subscribers within documents. Your application can use the publisher and subscriber options dialog boxes provided by the Edition Manager to make these choices available to the user. For example, a user can select Open Publisher within the subscriber options dialog box to access the document containing the publisher. Your application can also allow a user to cancel subscribers or publishers within documents, specify when to update an edition from a publisher, or specify when to update a subscriber with a new edition. These options are described later in this chapter.
1The Edition Manager
Using The Edition Manager
This section describes how your application can
n receive Apple events from the Edition Manager
n set up a section record and alias record for open documents containing sections
n save a document that contains sections
n open a document that contains sections
n read and write sections
n create a publisher within a document, create its edition container, and write data to it
n create a subscriber within a document and read its data from an edition
To begin, you must determine whether the Edition Manager is available on your system by using the Gestalt function. The Gestalt selector is gestaltEditionMgrAttr ('edtn'). If the response parameter returns 1 in the bit defined by the gestaltEditionMgrPresent constant (bit 0), the Edition Manager is present.
If the Edition Manager is present, load it into memory using the InitEditionPack function. This function determines whether your machine has enough space in the system heap for the Edition Manager to operate.
err := InitEditionPack;
If the InitEditionPack function returns noErr, you have enough space to load the package. If you do not have enough space, the application can either terminate itself or continue with the Edition Manager functionality disabled.
Receiving Apple Events From the Edition Manager
Applications that use the Edition Manager must support Apple events. This requires that your application support the required Open Documents event and Apple events sent by the Edition Manager. See the Apple Event Manager chapter in this volume for information on Apple events.
Apple events sent by the Edition Manager arrive as high-level events. The EventRecord data type defines the event record.
TYPE EventRecord =
RECORD
what: Integer; {kHighLevelEvent}
message: LongInt; {'sect'}
when: LongInt;
where: Point; {'read', 'writ', 'cncl', }
{ 'scrl'}
modifiers: Integer;
END;
The Edition Manager can send the following Apple events:
n Section Read events ('sect' 'read')
n Section Write events ('sect' 'writ')
n Section Cancel events ('sect' 'cncl')
n Section Scroll events ('sect' 'scrl')
Each time your application creates a publisher or a subscriber, the Edition Manager registers its section. When an edition is updated, the Edition Manager scans its list to locate registered subscribers. For each registered subscriber that is set up to receive updated editions automatically, your application receives a Section Read event.
If the Edition Manager discovers that an edition file is missing while registering a publisher, it creates a new edition file and sends the publisher a Section Write event.
When you receive a Section Cancel event, you need to cancel the specified section. Note that the current Edition Manager does not send you Section Cancel events, but you do need to provide a handler for future expansion.
If the user selects a subscriber within a document and then selects Open Publisher in the subscriber options dialog box, the publishing application receives the Open Documents event and opens the document containing the publisher. The publishing application also receives a Section Scroll event. Scroll to the location of the publisher, display this section on the user’s screen, and turn on its border.
See “Opening and Closing a Document Containing Sections” later in this chapter for detailed information on registering and unregistering a section and writing data to an edition. See “Using Publisher and Subscriber Options” later in this chapter for information on publisher and subscriber options.
After receiving an Apple event sent by the Edition Manager, use the Apple Event Manager to extract the section handle. In addition, you must also call the IsRegisteredSection function to determine whether the section is registered. It is possible (due to a race condition) to receive an event for a section that you recently disposed of or unregistered. One way to ensure that an event corresponds to a valid section is to call the IsRegisteredSection function after you receive an event. The Apple Event Manager chapter in this volume provides detailed information on Apple Event Manager routines.
err := IsRegisteredSection (sectionH);
Listing 1-1 illustrates how to use the Apple Event Manager and install an event handler to handle Section Read events. You can write similar code for Section Write events, Section Scroll events, and Section Cancel events.
Accepting Section Read events and verifying if a section is registered
THEN MyHandleSectionReadEvent := DoSectionRead(sectionH);
END ELSE
BEGIN
MyHandleSectionReadEvent := getErr;
END;
END; {MyHandleSectionReadEvent}
{The following routine should read in subscriber data and update }
{ its display.}
FUNCTION DoSectionRead(subscriber: SectionHandle) : OSErr;
BEGIN
{Your code here.}
END; {DoSectionRead}
{This is part of your Apple event–handling code.}
FUNCTION GetSectionHandleFromEvent(theAppleEvent: AppleEvent;
VAR sectionH: SectionHandle) :
OSErr;
VAR
ignoreType: DescType;
ignoreSize: Size;
BEGIN
{Parse section handle out of message buffer.}
GetSectionHandleFromEvent
:= AEGetParamPtr( theAppleEvent, {event to parse}
keyDirectObject, {Look for direct }
{ object.}
typeSectionH, {Want a SectionHandle }
{ type.}
ignoreType, {Ignore type it could }
{ get.}
@sectionH, {Put SectionHandle }
{ here.}
SizeOf(sectionH), {size of storage for }
{ SectionHandle}
ignoreSize); {Ignore storage it }
{ used.}
END; {GetSectionHandleFromEvent}
Creating the Section Record and Alias Record
Your application is responsible for creating a section record and an alias record for each publisher and subscriber section within an open document.
The section record identifies each section as a publisher or subscriber and provides identification for each section. The section record does not contain the data within the section; it describes the attributes of the section. Your application must provide its own method for associating the data within a section with its section record. Your application is also responsible for saving the data in the section.
The alias field of the section record contains a handle to its alias record. The alias record is a reference to the edition container from the document which contains the publisher or subscriber section. You should be familiar with the Alias Manager’s conventions for creating alias records and identifying files, folders, and volumes to locate files that have been moved, copied, or restored from backup.
When a user saves a document, your application should store all section records and alias records in the resource fork. Corresponding section records and alias records should have the same resource ID. This allows compatibility for future changes.
Figure 1-9 shows a document containing a publisher and subscriber, and the corresponding section records and alias records.
The SectionRecord data type defines the section record. A section record contains information to identify the data contained within a section as a publisher or a subscriber, a time stamp to record the last modification of the section, and unique identification for each section.
A document with a publisher and subscriber and its resource fork
TYPE SectionRecord =
RECORD
version: SignedByte; {always 1 in 7.0}
kind: SectionType; {publisher or subscriber}
mode: UpdateMode; {automatic or manual}
mdDate: TimeStamp; {last change in document}
sectionID: LongInt; {application-specific, }
{ unique per document}
refCon: LongInt; {application-specific}
alias: AliasHandle; {handle to alias record}
{The following fields are private and are set up by the }
{ RegisterSection function described later within this }
{ chapter. Do not modify the private fields.}
subPart: LongInt; {private}
nextSection: SectionHandle; {private, do not use as a }
{ linked list}
controlBlock: Handle; {may be used for comparison }
{ only}
refNum: EditionRefNum; {private}
END;
version Indicates the version of the section record, currently $01.
kind Defines the section type as either publisher or subscriber with the stPublisher or stSubscriber constant.
mode Indicates if editions are updated automatically or manually.
mdDate Indicates which version (modification date) of the section’s contents is contained within the publisher or subscriber. The mdDate is set to 0 when you create a new subscriber section, and is set to the current time when you create a new publisher. Be sure to update this field each time publisher data is modified. The section’s modification date is compared to the edition’s modification date to determine whether the section and the edition contain the same data. The section modification date is displayed in the publisher and subscriber options dialog boxes. See “Closing an Edition” later in this chapter for detailed information.
sectionID Provides a unique number for each section within a document. A simple way to implement this is to create a counter for each document that is saved to disk with the document. The counter should start at 1. The section ID is currently used as a tie breaker in the GoToPublisher function when there are multiple publishers to the same edition in a single document. The section ID should not be 0 or –1. See “Duplicating Publishers and Subscribers” later in this chapter for information on multiple publishers.
refCon Reference constant available for application-specific use.
alias Contains a handle to the alias record for a particular section within a document.
Whenever the user creates a publisher or subscriber, call the NewSection function to create the section record and the alias record.
The NewSection function creates a new section record (either publisher or subscriber), indicates whether editions are updated automatically or manually, sets the modification date, and creates an alias record from the document containing the section to the edition container.
The sectionDocument parameter can be NIL if your current document has never been saved. Use the AssociateSection function to update the alias record of a registered section when the user names or renames a document by choosing Save As from the File menu. If you are creating a subscriber with the initialMode parameter set to receive new editions automatically, your application receives a Section Read event each time a new edition becomes available for this subscriber.
If an error is encountered, the sectionH parameter is set to NIL. If not, sectionH contains the handle to the allocated section record.
Set the initialMode parameter to the update mode for each subscriber and publisher created. You can specify the update mode using these constants:
CONST sumAutomatic = 0; {subscriber receives new }
{ editions automatically}
sumManual = 1; {subscriber receives new }
{ editions manually}
pumOnSave = 0; {publisher sends new }
{ editions on save}
pumManual = 1; {publisher does not send }
{ new editions until user }
{ request}
See “Using Publisher and Subscriber Options” later in this chapter for detailed information on update modes for publishers and subscribers.
Saving a Document Containing Sections
When saving a document that contains sections, you should write out each section record as a resource of type 'sect' and write out each alias record as a resource of type 'alis' with the same ID as the section record. See the Resource Manager chapters in Volume I and this volume for detailed information on resources.
If a user closes a document that contains newly created publishers without attempting to save its contents, you should display an alert box similar to the one shown in Figure 1-10.
The new publisher alert box
If you keep the section records and alias records for each publisher and subscriber as resources, you can use the ChangedResource or WriteResource function. If you detach the section records and alias records from each section, you need to clone the handles and use the AddResource function. See the Resource Manager chapter in Volume V for detailed information on the ChangedResource, WriteResource, and AddResource functions.
Use the PBExchangeFiles function to ensure that each time you save a document that contains sections, the file ID remains the same. Saving a file typically involves creating a new file (with a temporary name), writing data to it, closing it, and then deleting the original file that you are replacing. You rename the temporary file with the original filename, which leads to a new file ID. The PBExchangeFiles function swaps the contents of the two files (even if they are open) by getting both catalog entries and swapping the allocation pointers. If the files are open, the file control block (FCB) is updated so that the reference numbers still access the same contents (under a new name). See the File Manager chapter in this volume for detailed information on the PBExchangeFiles function.
Listing 1-2 illustrates how to save a file that contains sections. As described earlier, you should write out the eligible section records and alias records as resources to allow for future compatibility. There are several different techniques for saving or adding resources; this listing illustrates one technique. The section handles are still valid after using the AddResource function because this listing illustrates just saving, not closing, the file.
Before you write out sections, you need to see if any publisher sections share the same control block. Publishers that share the same control block share the same edition.
If a user creates an identical copy of a file by choosing Save As from the File menu and does not make any changes to this new file, you simply use the AssociateSection function to indicate to the Edition Manager which document a section is located in.
Opening and Closing a Document Containing Sections
When opening a document that contains sections, your application should use the GetResource function to get the section record and the alias record for each publisher and subscriber. Set the alias field of the section record to be the handle to the alias. See the Resource Manager chapter in Volume I for detailed information on the GetResource function.
You also need to register each section using the RegisterSection function. The RegisterSection function informs the Edition Manager that a section exists.
The RegisterSection function adds the section record to the Edition Manager’s list of registered sections. This function assumes that the alias field of each section record is a handle to the alias record. The alias record is a reference to the edition container from the section’s document. If the RegisterSection function successfully locates the edition container for a particular section, the section is registered through a shared control block. The control block is a private field in the section record.
If the RegisterSection function cannot find the edition container for a particular subscriber, RegisterSection returns the containerNotFoundWrn result code. If the RegisterSection function cannot find the edition container for a particular publisher, RegisterSection creates an empty edition container for the publisher in the last place the edition was located. The Edition Manager sends your application a Section Write event for that section.
When a user attempts to open a document that contains multiple publishers to the same edition, you should warn the user by displaying an alert box (see “Duplicating Publishers and Subscribers” later in this chapter).
When a user opens a document that contains a subscriber (with an update mode set to automatic), receives a new edition, and then closes the document without making any changes to the file, you should update the document and simply allow the user to close it. You do not need to prompt the user to save changes to the file.
When closing a document that contains sections, you must unregister each section (using the UnRegisterSection function) and dispose of each corresponding section record and alias record.
err := UnRegisterSection (sectionH);
The UnRegisterSection function removes the section record from the list of registered sections and unlinks itself from the shared control block.
Listing 1-3 illustrates how to open an existing file that contains sections. As described earlier, you should retrieve the section and alias resources, connect the pair through the alias field of the section record, and register the section with the Edition Manager. There are many different techniques for retrieving resources; this listing shows one technique. If an alias was out of date and was updated by the Alias Manager during the resolve, the Edition Manager sets the aliasWasUpdated parameter of the RegisterSection function to TRUE. This means that you should save the document. Additionally, your application must maintain its own list of registered sections for each open document that contains sections. You use this list to write out new editions for updated publishers within a document.
{If the alias has changed, make note of this. It is }
{ important to know this when you save. AliasHasChanged is }
{ a routine that will do this.}
IF aliasWasUpdated THEN AliasHasChanged(sectionH);
END; {for}
END; {OpenExistingDocument}
Reading and Writing a Section
Your application writes publisher data to an edition. New publisher data replaces the previous contents of the edition, making the previous edition information irretrievable. Your application reads data from an edition for each subscriber within a document.
The following sections describe how to
n use different formats to write to or read from an edition
n open an edition to initiate writing or reading
n set a format mark
n write to or read from an edition
n close an edition after successfully writing or reading data
Formats in an Edition
You can write data to an edition in several different formats. These formats are the same as Clipboard formats. Clipboard formats are indicated by a four-character tag.
Typically, when a user copies data, you identify the Clipboard formats and then write the data to scrap. With the Edition Manager, when a user decides to publish data, you identify the Clipboard formats and then write the data to an edition. You can write multiple formats of the same data.
For an edition, you should write your preferred formats first. In general, to write data to an edition, your application should use either 'TEXT' format or 'PICT' format. This allows your application to share data with most other applications. To subscribe to an edition, your application should be able to read both 'TEXT' and 'PICT' files. In addition, your application can write any other private formats that you want to support.
Clipboard formats are described in the Scrap Manager chapter in Volume I.
A few special formats are defined as constants.
CONST kPublisherDocAliasFormat = 'alis'; {alias record from the }
{ edition to publisher}
kPreviewFormat = 'prvw'; {'PICT' thumbnail }
{ sketch}
kFormatListFormat = 'fmts'; {lists all available }
{ formats}
The kPublisherDocAliasFormat ('alis') format is written by the Edition Manager. It is an alias record from the edition to the publisher’s document. Appended to the end of the alias is the section ID of the publisher, which the Edition Manager uses to distinguish between multiple publishers to a single edition. You should discourage users from making multiple copies of the same publisher. See “Duplicating Publishers and Subscribers” later in this chapter for detailed information.
The kPreviewFormat ('prvw') format should be written by any application that publishes large amounts of data that may be slow to draw a preview. This format holds a preview of the edition data that is displayed in the preview area of the subscriber dialog box. This format is actually a 'PICT' file that is generated by the publishing application and displays well in a rectangle of 120 by 120 pixels. You can also use this 'PICT' file to display subscriber data within a document (to save space).
To draw a preview in the 'prvw' format, the Edition Manager calls DrawPicture with a 120 by 120 rectangle. To draw a preview in the 'PICT' format, the Edition Manager examines the picture’s bounding rectangle and calls DrawPicture with a rectangle that scales the picture proportionally and centers it in a 120 by 120 area.
The kFormatListFormat ('fmts') format is a virtual format that is read but never written. It is a list of all the formats and their lengths. Applications can use this format in place of the EditionHasFormat function (described in “Choosing Which Edition Format to Read” later in this chapter), which provides a procedural interface to determine which formats are available.
If your application can read two or more of the available formats, use 'fmts' to determine the priority of these formats for a particular edition. The order of 'fmts' reflects the order in which the formats were written.
The FormatsAvailable data type defines a record for the 'fmts' format.
TYPE FormatsAvailable = ARRAY[0..0] OF
RECORD
theType: FormatType; {format type for an edition}
theLength: LongInt; {length of edition format }
{ type}
END;
For example, an edition container may have a format type 'TEXT' of length 100, and a format type 'styl' of length 32. A subscriber to this edition can open it and then read the format type 'fmts' to list all available formats. In this example, it returns 16 bytes: 'TEXT' $00000064 'styl' $00000020.
Opening an Edition
For a publisher, use the OpenNewEdition function to initiate the writing of data to an edition.
The publisherSectionH parameter is the publisher section that you are writing to the edition. The fdCreator parameter is the Finder<Superscript\>\xaa creator type of the new edition icon.
The publisherSectionDocument parameter is the document that contains the publisher. This parameter is used to create an alias from the edition to the publisher’s document. If you pass NIL for publisherSectionDocument, an alias is not made in the edition file. The refNum parameter returns the reference number for the edition.
For a subscriber, use the OpenEdition function to initiate the reading of data from an edition.
err := OpenEdition (subscriberSectionH, refNum);
The subscriberSectionH parameter is a handle to the section record for a given section. The refNum parameter returns the reference number for the edition.
The user may rename or move the edition in the Finder. Before writing to or reading data from an edition, the Edition Manager verifies the name of the edition. This process is referred to as synching or synchronization. Synching ensures that the Edition Manager’s existing edition names correspond to the Finder’s existing edition names by updating the control block.
Format Marks
Each format has its own mark. The mark indicates the next position of a read or write operation. Initially, a mark automatically defaults to 0. After reading or writing data, the format mark is set past the last position written to or read from. The mark is similar to the File Manager’s current read or write position marker for a data fork. Any time that an edition is open (after calling the OpenEdition or the OpenNewEdition function), any of the marks for each format can be queried or set.
To set the current mark for a section format to a new location, use the SetEditionFormatMark function.
With the Edition Manager, you can read or write data a few bytes at a time instead of putting data into one block as the Scrap Manager does. This model is similar to the data fork of a Macintosh file. You can read sequentially by setting the mark to 0 and repeatedly calling read, or you can jump to a specific offset by setting the mark there. The Edition Manager also adds the capability to stream multiple formats by keeping a separate mark for each format. This allows you to write a few bytes of one format and then write a few bytes of another format, and so forth.
Once you have opened the edition container for a particular publisher, you can begin writing data to the edition. Use the WriteEdition function to write publisher data to an edition.
The WriteEdition function writes the specified format (beginning at the current mark for that format type) from the buffer pointed to by the buffPtr parameter up to buffLen bytes.
After you open the edition container for a subscriber and determine which formats to read, use the ReadEdition function to read edition data.
The ReadEdition function reads the data with the specified format (whichFormat) from the edition into the buffer. The ReadEdition function begins reading at the current mark for that format and continues to read up to buffLen bytes. The actual number of bytes read is returned in the buffLen parameter. Once the buffLen parameter returns a value smaller than the value you have specified, there is no additional data to read, and the ReadEdition function returns a noErr result code.
Closing an Edition
When you are done writing to or reading data from an edition, call the CloseEdition function.
err := CloseEdition (whichEdition, successful);
Each time a user edits a publisher within a document, you must update the modification date in the section record (even if the data is not yet written). When the update mode is set to Manually, the user can compare the modification dates for a publisher and its edition in the publisher options dialog box. One modification date indicates when the publisher last wrote data to the edition, and the other modification date indicates when the publisher section was last edited.
If the successful parameter for a publisher is TRUE, the CloseEdition function makes the newly written data available to subscribers and sets the modification date in the mdDate field of the edition to correspond to the modification date of the publisher’s section record. If the two dates differ, the Edition Manager sends a Section Read event to all current subscribers.
If the successful parameter for a subscriber is TRUE, the CloseEdition function sets the modification date of the subscriber’s section record to correspond to the modification date of the edition.
If you cannot successfully read from or write data to an edition, set the successful parameter to FALSE. For a publisher, data is not written to the edition, but it should still be saved with the document that contains the section. When the document is next saved, data can then be written to the edition. See “Closing an Edition After Reading or Writing” later in this chapter for additional information on the CloseEdition function.
Creating a Publisher
You need to support a Create Publisher menu command in the Edit menu. When a user selects a portion of a document and chooses Create Publisher from this menu, you should display the publisher dialog box on the user’s screen. The Create Publisher menu command should remain dimmed until the user selects a portion of a document.
Use the NewPublisherDialog function to display the publisher dialog box on the user’s screen. This function is similar to the CustomPutFile procedure described in the Standard File Package chapter in this volume.
err := NewPublisherDialog (reply);
The dialog box contains space for a preview (a thumbnail sketch) of the edition and a space for the user to type in the name of the edition in which to write the publisher data. Figure 1-11 illustrates a sample publisher dialog box.
A sample publisher dialog box
The NewPublisherDialog function displays the preview (provided by your application), a text box with the default name of the edition (provided by your application), and handles all user input until the user clicks Publish or Cancel.
You pass a new publisher reply record as a parameter to the NewPublisherDialog function.
TYPE NewPublisherReply =
RECORD
canceled: Boolean; {user canceled dialog box}
replacing: Boolean; {user chose existing }
{ filename for an edition}
usePart: Boolean; {always FALSE in version 7.0}
preview: Handle; {handle to 'prvw', 'PICT', }
{ 'TEXT', or 'snd' data}
previewFormat: FormatType; {type of preview}
container: EditionContainerSpec;
{edition chosen}
END;
You fill in the usePart, preview, previewFormat, and container fields of the new publisher reply record.
Always set the usePart field to FALSE. The preview field contains either NIL or the data to display in the preview. The previewFormat field should contain 'PICT', 'TEXT', or 'prvw'.
Set the container field to be the default name and folder for the edition. The default name should reflect the data contained in the publisher. For example, if a user publishes a bar chart of sales information entitled “sales data,” then the default name for the edition could also be “sales data.” Otherwise, you should use the document name followed by a hyphen (-) and a number to establish uniqueness. For example, your default name could be “January Totals - 3.”
If the document has not been saved, the default name should be “untitled edition <n>” where n is a number to establish uniqueness. The default folder should be the same as the edition for the last publisher created in the same document. If this is the first publisher in the document, the default folder should be the same folder that the document is in.
The canceled field of the new publisher reply record indicates whether the user canceled from the dialog box. The replacing field indicates that the user chose to replace an existing edition file. If replacing returns FALSE, call the CreateEditionContainerFile function to create an edition file.
The container field is of data type EditionContainerSpec.
TYPE EditionContainerSpec =
RECORD
theFile: FSSpec; {file containing edition }
{ data}
theFileScript: ScriptCode; {script code of filename}
thePart: LongInt; {which part of file, }
{ always kPartsNotUsed}
thePartName: Str31; {not used in version 7.0}
thePartScript: ScriptCode; {not used in version 7.0}
END;
The field theFile is of type FSSpec. See the File Manager chapter in this volume for further information on file system specification records.
You identify the edition using a volume reference number, directory ID, and filename. When specifying an edition, follow the standard conventions described in the File Manager chapter of this volume.
After filling in the fields of the new publisher reply record, pass it as a parameter to the NewPublisherDialog function, which displays the publisher dialog box.
err := NewPublisherDialog (reply);
After displaying the publisher dialog box, use the CreateEditionContainerFile function to create the edition container, and then use NewSection function to create the section record and the alias record. See “Creating the Section Record and Alias Record” earlier in this chapter for detailed information.
In response to the user selecting the Create Publisher menu item, this code illustrates how your application might set up the preview for the edition, set the default name for the edition container, and call an application-defined function (DoNewPublisher function) to display the publisher dialog box on the user’s screen. An application might call the DoNewPublisher function as a result of the user making a menu selection to create a publisher or in response to handling the Create Publisher event. See the Apple Event Manager chapter in this volume for an example handler that handles the Create Publisher event.
VAR
thisDocument: MyDocumentInfoPtr;
promptForDialog: Boolean;
preview: Handle;
previewFormat: FormatType;
defaultLocation: EditionContainerSpec;
BEGIN
{Get a preview to show the user. The MyGetPreviewForSelection }
This function creates an edition container. The edition container is empty (that is, it does not contain any formats) at this time.
To create a customized icon for the edition container, put the creator signature of your application with the icon in your application’s bundle. See the Finder Interface chapter in this volume for additional information. Depending on the contents of the edition, the file type will be 'edtp' (for graphics), 'edtt' (for text), or 'edts' (for sound).
After creating the edition container, use the NewSection function to create the section record and alias record for the section.
Listing 1-4 illustrates how to create a publisher. The DoNewPublisher function shown in the listing is a function provided by an application. Note that an application might call the DoNewPublisher function as a result of the user making a menu selection to create a publisher or in response to handling the Create Publisher event. See the Apple Event Manager chapter in this volume for an example handler that handles the Create Publisher event.
The parameters to the DoNewPublisher function include a pointer to information about the document, a Boolean value that indicates if the function should display the new publisher dialog box, the preview for the edition, the preview format, and an edition container.
The function displays the publisher dialog box if requested, letting the user accept or change the name of the edition and the location where the edition should reside. Use the CreateEditionContainerFile function to create the edition with the given name and location. Use the NewSection function to create a new section for the publisher.
After the section is created, you must write out the edition data. Be sure to add the newly created section to your list of sections for this document. There are several different techniques for creating publishers and unique IDs; this listing displays one technique.
Creating a publisher
FUNCTION DoNewPublisher(thisDocument: MyDocumentInfoPtr;
promptForDialog: Boolean; preview: Handle;
previewFormat: FormatType;
editionSpec: EditionContainerSpec) : OSErr;
VAR
getLastErr, dialogErr: OSErr;
createErr, sectionErr: OSErr;
resID: Integer;
thisSectionH: SectionHandle;
reply: NewPublisherReply;
BEGIN
{Set up info for new publisher reply record}
reply.replacing := FALSE;
reply.usePart := FALSE;
reply.preview := preview;
reply.previewFormat := previewFormat;
reply.container := editionSpec;
IF promptForDialog THEN
BEGIN {user interaction is allowed}
{Display dialog box and let user select.}
dialogErr := NewPublisherDialog(reply);
{Dispose of preview data handle.}
DisposHandle(reply.preview);
{There's usually no error returned here, but if there is, }
{ then it makes no sense to continue with this operation.}
IF dialogErr <> noErr THEN MyErrHandler(dialogErr);
{Do nothing if user canceled.}
IF reply.canceled THEN
BEGIN
DoNewPublisher := userCanceledErr;
EXIT(DoNewPublisher);
END;
END;
{If user wants to replace an existing file, don't create one.}
{Remember that the section and alias records need to be }
{ saved as resources when the user saves the document.}
{Set the function result appropriately}
DoNewPublisher := MyGetLastError;
END; {DoNewPublisher}
Opening an Edition Container to Write Data
Several routines are required to write (publish) data from a publisher to an edition container. Before writing data to an edition, you must use the OpenNewEdition function. This function should be used only for a publisher within a document. Use this function to initiate the writing of data to an edition.
A user may try to save a document containing a publisher that is unable to write its data to an edition—because another publisher (that shares the same edition) is writing, another subscriber (that shares the same edition) is reading, or a publisher located on another computer is registered to the section. In such a case, you may decide to refrain from writing to the edition so that the user does not have to wait. You should also refrain from displaying an error to the user. The contents of the publisher are saved to disk with the document. The next time that the user saves, you can write the publisher data to the edition. You should discourage users from making multiple copies of the same publisher and pasting them in the same or other documents by displaying an alert box (see “Duplicating Publishers and Subscribers” later in this chapter).
If a user clicks Send Edition Now within the publisher options dialog box (to write publisher data to an edition manually), and the publisher is unable to write its data to its edition (for any of the reasons outlined above), you should display an error message.
After you are finished writing data to an edition, use the CloseEdition function to close the edition.
Listing 1-5 illustrates how to write data to an edition. As described earlier, you must open the edition, write each format using the WriteEdition function, and close the edition using the CloseEdition function. This listing shows how to write text only. If the edition is written successfully, subscribers receive Section Read events.
{There were problems writing; simply close the edition. }
{ When successful = FALSE, the edition data <> section }
{ data. Note: this isn't fatal or bad; it just means }
{ that the data wasn't written and no Section Read events }
{ will be generated.}
closeErr := CloseEdition(eRefNum, FALSE);
END ELSE
BEGIN
{The write was successful; now close the edition. }
{ When successful = TRUE, the edition data = section data.}
{ This edition is now available to any subscibers. }
{ Section Read events will be sent to current subscribers.}
closeErr := CloseEdition(eRefNum, TRUE);
END;
END; {DoWriteEdition}
Creating a Subscriber
You need to create a Subscribe To menu command in the Edit menu. When a user chooses Subscribe To from this menu, your application should display the subscriber dialog box on the user’s screen.
Use the NewSubscriberDialog function to display the subscriber dialog box on the user’s screen. This function is similar to the CustomGetFile procedure described in the Standard File Package chapter in this volume.
To create a subscriber, you must get information from the user, such as the name of the edition being subscribed to. The dialog box displays a listing of all available editions and allows the user to see a preview (thumbnail sketch) of the edition selected. Figure 1-12 shows a sample subscriber dialog box.
A sample subscriber dialog box
The subscriber dialog box allows the user to choose an edition to subscribe to. The NewSubscriberDialog function handles all user interaction until a user clicks Subscribe or Cancel. When a user selects an edition container, the Edition Manager accesses the preview for the edition container (if it is available) and displays it.
You pass a new subscriber reply record as a parameter to the NewSubscriberDialog function.
TYPE NewSubscriberReply =
RECORD
canceled: Boolean; {user canceled dialog }
{ box}
formatsMask: SignedByte; {formats required}
container: EditionContainerSpec;
{edition selected}
END;
The canceled field returns a Boolean value of TRUE if the user clicked Cancel. To indicate which edition format types (text, graphics, or sound) your application can read, you set the formatsMask field to one or more of these constants:
CONST kPICTformatMask = 1; {Can subscribe to 'PICT', }
kTEXTformatMask = 2; { 'TEXT', and }
ksndFormatMask = 4; { 'snd '.}
To support a combination of formats, add the constants together. For example, a formatsMask of 3 displays both graphics and text edition format types in the subscriber dialog box.
The container field is of data type EditionContainerSpec. You must initialize the container field with the default edition volume reference number, directory ID, filename, and part. To do so, use the GetLastEditionContainerUsed function to obtain the name of the last edition displayed in the dialog box.
err := GetLastEditionContainerUsed (container);
This function returns the last edition container for which a new subscriber was created using the NewSection function. If there is no last edition, or if the edition was deleted, GetLastEditionContainerUsed still returns the correct volume reference number and directory ID to use, but leaves the filename blank and returns the fnfErr result code.
The container field is of data type EditionContainerSpec.
TYPE EditionContainerSpec =
RECORD
theFile: FSSpec; {file containing edition }
{ data}
theFileScript: ScriptCode; {script code of filename}
thePart: LongInt; {which part of file, }
{ always kPartsNotUsed}
thePartName: Str31; {not used in version 7.0}
thePartScript: ScriptCode; {not used in version 7.0}
END;
The field theFile is of type FSSpec. See the File Manager chapter in this volume for further information on file system specification records.
After filling in the fields of the new subscriber reply record, pass it as a parameter to the NewSubscriberDialog function, which displays the subscriber dialog box.
err := NewSubscriberDialog (reply);
After displaying the subscriber dialog box, call the NewSection function to create the section record and the alias record. See “Creating the Section Record and Alias Record” earlier in this chapter for detailed information.
If the subscriber is set up to receive new editions automatically (not manually), the Edition Manager sends your application a Section Read event. Whenever your application receives a Section Read event, it should read the contents of the edition into the subscriber.
Listing 1-6 illustrates how to create a subscriber. As described earlier, you must set up and display the subscriber dialog box to allow the user to subscribe to all available editions. After your application creates a subscriber, your application receives a Section Read event to read in the data being subscribed to. Be sure to add the newly created section to your list of sections for this file. There are many different techniques for creating subscribers and unique IDs; this listing displays one technique.
{Remember that you will receive a Section Read event to read }
{ in the edition that you just subscribed to because the
{ initial mode is set to sumAutomatic.}
{Remember that the section and alias records need to be saved }
{ as resources when the user saves the document.}
END; {DoNewSubscriber}
Opening an Edition Container to Read Data
Before reading data from an edition, you must use the OpenEdition function. Your application should only use this function for a subscriber. Use this function to initiate the reading of data from an edition.
err := OpenEdition (subscriberSectionH, refNum);
As a precaution, you should retain the old data until the user can no longer undo. This allows you to undo changes if the user requests it.
Your application can supply a procedure such as DoReadEdition to read in data from the edition to a subscriber. When your application opens a document containing a subscriber that is set up to receive new editions automatically, the Edition Manager sends you a Section Read event if the edition has been updated. The Section Read event supplies the handle to the section that requires updating. Listing 1-7 provides an example of reading data from an edition.
Choosing Which Edition Format to Read
After your application opens the edition container for a subscriber, it can look in the edition for formats that it understands. To accomplish this, use the EditionHasFormat function.
The EditionHasFormat function returns the noTypeErr result code if a requested format is not available. If the requested format is available, this function returns the noErr result code, and the formatSize parameter contains the size of the data in the specified format or kFormatLengthUnknown (–1), which signifies that the size is unknown.
After your application opens the edition container and determines which formats it wants to read, call the ReadEdition function to read in the edition data. See “Reading and Writing Edition Data” earlier in this chapter for detailed information.
After you have completed writing the edition data into the subscriber section, call the CloseEdition function to close the edition. See “Closing an Edition” earlier in this chapter for detailed information.
Listing 1-7 illustrates how to read data from an edition. As described earlier, you must open the edition, determine which formats to read, use the ReadEdition function to read in data, and then use the CloseEdition function to close the edition. This listing shows how to read only text.
{The read was successful; now close the edition. When}
{ successful = TRUE, the section data = edition data.}
closeErr := CloseEdition(eRefNum, TRUE);
EXIT(DoReadEdition);
END;
END;
{'TEXT' format wasn't found or read error; just close }
{ the edition. FALSE tells the Edition Manager that your }
{ application did not get the latest edition.}
closeErr := CloseEdition(eRefNum, FALSE);
END; {DoReadEdition}
Using Publisher and Subscriber Options
There are special options associated with publishers and subscribers within documents. Your application can use the publisher and subscriber options dialog boxes provided by the Edition Manager to make these choices available to the user. You should make these dialog boxes available to the user by creating a menu command in the Edit menu that toggles between Publisher Options (when the user has selected a publisher within a document) and Subscriber Options (when a user has selected a subscriber within a document).
When a user chooses these menu commands, you need to display the corresponding publisher or subscriber options dialog box. Use the SectionOptionsDialog function to display the appropriate dialog box on the user’s screen.
err := SectionOptionsDialog (reply);
Each dialog box contains information regarding the section and its edition. Figure 1-13 shows the publisher options dialog box with the update mode set to On Save.
The publisher options dialog box with update mode set to On Save
Figure 1-14 shows the publisher options dialog box with the update mode set to Manually.
The publisher options dialog box with update mode set to Manually
As a shortcut for the user, you should display the publisher options dialog box when the user double-clicks on a publisher section within a document. Figure 1-15 shows the subscriber options dialog box with the update mode set to Automatically.
The subscriber options dialog box with update mode set to Automatically
Figure 1-16 shows the subscriber options dialog box with the update mode set to Manually.
The subscriber options dialog box with update mode set to Manually
As a shortcut for the user, you should display the subscriber options dialog box when the user double-clicks on a subscriber section within a document.
You pass a section options reply record as a parameter to the SectionOptionsDialog function.
TYPE SectionOptionsReply =
RECORD
canceled: Boolean; {user canceled dialog box}
changed: Boolean; {changed section record}
sectionH: SectionHandle; {handle to the specified }
{ section record}
action: ResType; {action codes}
END;
Set the sectionH parameter to the handle to the section record for the section the user selected.
Upon return of the SectionOptionsDialog function, the canceled and changed fields are set. If the canceled parameter is set to TRUE, the user canceled the dialog box. Otherwise, this parameter is FALSE. If the changed parameter is TRUE, the section record is changed. For example, the user may have changed the update mode.
The action parameter contains the code for one of five user actions. All action codes dismiss the publisher and subscriber options dialog boxes when complete.
n action code is 'read' for user selection of the Get Edition Now button
n action code is 'writ' for user selection of the Send Edition Now button
n action code is 'goto' for user selection of the Open Publisher button
n action code is 'cncl' for user selection of the Cancel Publisher or Cancel Subscriber button
n action code is ' ' ($20202020) for user selection of the OK button
Listing 1-8 shows an example of how your application can respond to the action codes received from the section options reply record. There are several different techniques that your application can use to accomplish this—this listing shows one technique.
{Same comment as above. Pass control to MyErrHandler }
{ if there's an error.}
IF gpsErr <> noErr THEN MyErrHandler(gpsErr);
EXIT(DoOptionsDialog);
END;
IF (action = 'cncl') THEN
BEGIN {User selected Cancel Publisher or Cancel }
{ Subscriber button.Call the UnRegisterSection }
{ function and dispose of the section record and }
{ the alias record.}
EXIT(DoOptionsDialog);
END;
END; {DoOptionsDialog}
The following sections describe the features of the publisher and subscriber options dialog boxes.
Publishing a New Edition While Saving or Manually
By default, your application should write publisher data to an edition each time the user saves the document and the contents of the publisher differ from the latest edition. In the publisher options dialog box, the user can choose to write new data to an edition each time the document is saved (by clicking On Save) or only when the user specifically requests it (by clicking Manually).
When the update mode is set to manual, a user must click the Send Edition Now button within the publisher options dialog box to write publisher data to an edition. When a user clicks Send Edition Now, the section options reply record contains the action code 'writ'. Write out the new edition beginning with the OpenNewEdition function. Writing to an edition manually is useful when a user tends to save a document numerous times while revising it.
Each time the user saves the document, check the update mode of the publisher section. If the publisher section sends its data to an edition on save, check to see whether the publisher data has changed since it was last written out to the edition. If so, write out the new edition.
In addition, you may also support a Stop All Editions menu command to provide a method for temporarily suspending all update activity. See “Publishers, Subscribers, and Editions” earlier in this chapter for additional information.
Subscribing to an Edition Automatically or Manually
By default, your application should subscribe to an edition each time new edition data becomes available. In the subscriber options dialog box, the user can choose to read new data from an edition as the data is available (by clicking Automatically) or only when the user specifically requests it (by clicking Manually).
When the update mode is set to manual, the user must click the Get Edition Now button within the subscriber options dialog box to receive new editions. When a user clicks this button, the section options reply record contains the action code 'read'. Read in the new edition beginning with the OpenEdition function. See “Opening an Edition Container to Read Data” earlier in this chapter for detailed information.
When the update mode is set to automatic, your application receives a Section Read event each time a new edition becomes available. In response, you should read the new edition data beginning with the OpenNewEdition function.
Your application does not receive Section Read events for subscribers that receive new editions manually.
You may also support a Stop All Editions menu command to provide a method for temporarily suspending all update activity. See “Publishers, Subscribers, and Editions” earlier in this chapter for additional information.
Canceling Sections Within Documents
The option of canceling publishers and subscribers is available to the user through the Cancel Publisher and Cancel Subscriber buttons in the corresponding options dialog boxes. When the user wants to cancel the publisher or cancel the subscriber within a document, the action code of the section options reply record is 'cncl'. See “Relocating an Edition” later in this chapter for additional information on canceling a section.
When a user cancels a section (either a publisher or subscriber) and then saves the document, or when a user closes an untitled document (which contains newly created sections) without saving, you must unregister each corresponding section record and alias record using the UnRegisterSection function. In addition, you should also delete the section record and alias record using the DisposHandle procedure. See the Memory Manager chapter in Volume I for additional information on the DisposHandle procedure. When a user cancels a publisher section and then saves the document, or when a user closes an untitled document (which contains newly created publishers) without saving, you must also delete any corresponding edition containers (in addition to deleting section records and alias records).
Do not delete an edition container file, section record, or alias record until the user saves the document—the user may decide to undo changes before saving the document.
To locate the appropriate edition container to be deleted (before you use the UnRegisterSection function), use the GetEditionInfo function.
err := GetEditionInfo (sectionH, editionInfo);
The editionInfo parameter is a record of data type EditionInfoRecord.
TYPE EditionInfoRecord =
RECORD
crDate: TimeStamp; {date edition container }
{ was created}
mdDate: TimeStamp; {date of last change}
fdCreator: OSType; {file creator}
fdType: OSType; {file type}
container: EditionContainerSpec; {the edition}
END;
The GetEditionInfo function returns the edition container as part of the edition information.
The crDate field contains the creation date of the edition. The mdDate field contains the modification date of the edition.
The fdType and the fdCreator fields are the type and creator of the edition file. The container field includes a volume reference number, directory ID, filename, script, and part number for the edition.
To remove the edition container, use the DeleteEditionContainerFile function.
err := DeleteEditionContainerFile (editionFile);
Locating a Publisher Through a Subscriber
The user can locate a publisher from a subscriber within a document by clicking the Open Publisher button in the subscriber options dialog box. As a shortcut, Apple suggests that you also allow the user to locate a publisher when the user selects a subscriber within a document and presses Option–double-click.
When the action code of the SectionOptionsReply record is 'goto', use the GoToPublisherSection function.
err := GoToPublisherSection (container);
The GoToPublisherSection function locates the correct document by resolving the alias in the edition, and it launches the document’s application if necessary (the Edition Manager sends an Open Documents event). The Edition Manager then sends the publishing application a Section Scroll event. If the document containing the requested publisher is located on the same computer as its subscriber, the document opens and scrolls to the location of the publisher. If the document containing the requested publisher is located on a shared volume (using file sharing), the document opens and scrolls to the location of the publisher only if the user has privileges to open the document from the Finder.
You need to provide the GoToPublisherSection function with the edition container. To accomplish this, use the GetEditionInfo function. See the previous section, “Canceling Sections Within Documents,” for information on the GetEditionInfo function.
Renaming a Document Containing Sections
If a user renames a document that contains sections by choosing Save As from the File menu, or if a user pastes a portion of a document that contains a section into another document, use the AssociateSection function.
Use the AssociateSection function to update the alias record of a registered section.
The AssociateSection function internally calls the UpdateAlias function. It is also possible to update the alias record using the Alias Manager (see the Alias Manager chapter in this volume for additional information).
Displaying Publisher and Subscriber Borders
Each publisher and subscriber within a document should have a border that appears when a user selects the contents of these sections. You should display a publisher border as 3 pixels wide with 50 percent gray lines and a subscriber border as 3 pixels wide with 75 percent gray lines. Separate the contents of the section from the border itself with one pixel of white space. To create your borders, you should use patterns—not colors. Depending on the user’s monitor type, colors may not be distinguishable.
In general, borders for publishers and subscribers should behave like the borders of 'PICT' graphics within a word-processing document. A border should appear when the user clicks within the content area of a publisher or a subscriber and disappear when the user clicks outside the content area of a section. You can also make all publisher and subscriber borders appear or disappear by implementing an optional Show/Hide Borders menu command. Figure 1-17 displays the Edition Manager Show/Hide Borders menu command in the Edit menu.
Edit menu with Show/Hide Borders menu command
Depending on your application, you may choose to include resize handles or similar components in your borders. See “Object-Oriented Graphics Borders” later in this chapter for an example of resize handles.
Whenever a user selects a portion of a publisher or inserts a cursor into the publisher, you should display the border as 50 percent gray. A user can copy the contents of a publisher or subscriber without copying the section itself by selecting the data, copying, and then pasting the data in a new location. A user can cut and paste a selection that contains an entire publisher or subscriber, but you should discourage users from making multiple copies of a publisher. See “Duplicating Publishers and Subscribers” later in this chapter for detailed information.
When the user modifies a publisher, your application should grow or shrink its border to accommodate the new dimension of the section.
You should display only one publisher border within a document at a time. If a cursor is inserted within a publisher that is contained within a larger publisher, you should display only the smaller, internal publisher border. If it is absolutely necessary to display all section borders within a document at the same time, you can create a Show/Hide Borders menu item.
You do not need to provide support for publishers contained within other publishers. If you do not, you should dim the Create Publisher menu command (to indicate that it is not selectable) when a user attempts to create a publisher within an existing publisher.
Figure 1-18 shows the recommended border behavior for publishers when borders are shown, when a user selects the contents of a section, and when a user selects data within a document that includes a publisher section.
Publisher borders
Figure 1-19 shows the recommended border behavior for subscribers when borders are shown, when a user selects the contents of a section, and when a user selects data within a document that includes a subscriber section.
Subscriber borders
If a user tries to select only a portion of a subscriber, you should highlight the entire contents of the subscriber. A user cannot edit the data contained within a subscriber. See “Modifying a Subscriber” later in this chapter for detailed information.
If a user cancels a section using the publisher or subscriber options dialog box, your application should leave the contents of the section within the document, but you should be sure to remove the borders from this data, as it is no longer considered a section.
Generally, the appearance and function of publisher and subscriber borders should be the same across different applications. See the following sections entitled “Text Borders,” “Spreadsheet Borders,” “Object-Oriented Graphics Borders,” and “Bitmapped Graphics Borders” for descriptions of specialized features for publisher and subscriber borders in word processing, spreadsheet, or graphics applications.
Text Borders
In word-processing documents, a publisher may contain other publishers. However, one publisher should not overlap another publisher. You should display only one publisher border at a time. If an insertion point is placed within a publisher that is encompassed by another larger publisher, you should display only the smaller internal publisher border.
In exceptional cases, it may be necessary to display more than one publisher or subscriber border at a time. For example, a publisher may consist of a paragraph that includes a marker for a footnote. The data contained within the footnote should also be considered part of the publisher. When a user selects the paragraph, you should simultaneously display a border around the footnote.
The border of a publisher that contains text should be located between characters within the text. The insertion point, when placed on such a boundary, should gravitate toward the publisher. That is, a click in front (to the left) of a publisher border should place the cursor inside the publisher, so that subsequent typing goes inside the publisher. Clicking at the end (to the right) of a publisher border should also place the cursor inside the publisher.
Whenever two separate borders are adjacent to one another (side by side), the boundary click should go in between them. This is also true for a border that is next to other nontextual aspects of a document, such as 'PICT' graphics or page breaks.
When a user removes information from a publisher that contains text data, the border should become smaller to accommodate the new text. When a user adds information to the publisher, the border should grow to show the enlarged area of the publisher. The insertion point should remain within the publisher.
If a user highlights the entire contents of a publisher and then chooses Cut from the Edit menu, you should not delete the publisher border within the document. The user may intend to delete the existing publisher data and replace it with new data, or the user may want to move the entire publisher and its data to a new location. Figure 1-20 shows this state.
A publisher with contents removed
You should leave the cursor inside the small publisher border for further typing. If the user inserts the cursor in a new location (instead of typing data inside the existing border), you need to remove the empty publisher border from the document to allow the user to move the publisher. This effectively deletes the publisher from the document. If the user pastes the publisher that is currently held in the Clipboard, you should recreate its border. If the user cuts or copies other data from the document before pasting the publisher from the Clipboard, the publisher should be removed from the Clipboard.
Spreadsheet Borders
Borders around spreadsheet data or other data in arrays should look and behave very much like text borders. Figure 1-21 shows a typical border within a spreadsheet document.
A publisher border within a spreadsheet document
Note that the border goes below the column headers (A, B, C, D) and to the right of the row labels (1, 2, 3, 4)—it should not overlap these cell boundaries. The border at the bottom and the border on the right side can be placed within the adjacent cells (outside of the cells that constitute the publisher).
In contrast to word-processing applications, borders in spreadsheet documents (or other documents with array data) can overlap. That is, a user can select a row of cells to be a publisher and an overlapping column of those cells to be another publisher. You should never display more than one publisher border at a time. When a user selects a spreadsheet cell that is part of more than one publisher, you should display only the border of the publisher that was last edited. (This can be accomplished by comparing the modification dates of the publishers.)
If it is absolutely necessary to display all section borders within a document at the same time, you can create a Show/Hide Borders command in the Edit menu to toggle all borders on and off.
When data is added to or deleted from a publisher that consists of a spreadsheet cell or other array, its border should grow or shrink to accommodate the addition or deletion of data. A publisher should behave like a named range in a spreadsheet. For example, if a user cuts a row within a publisher that consists of a named range in a spreadsheet, you should shrink the publisher data and its border correspondingly.
When a user cuts a publisher and its entire contents within a spreadsheet document, the entire section should be held in the Clipboard. Do not leave an empty publisher border in a spreadsheet (as recommended for text borders). If a user attempts to paste a copy of an existing publisher, you should warn the user by displaying an alert box (see “Duplicating Publishers and Subscribers” later in this chapter).
Object-Oriented Graphics Borders
In an object-oriented drawing application, the publisher border should fit just around the selected objects.
You can provide resize handles that appear with all drawing objects to allow the user to resize the border of a publisher. Figure 1-22 shows a publisher border with resize handles.
A publisher border with resize handles
A user can create freeform graphics within drawing applications that cause publisher borders to seemingly float over the area the user publishes. The border acts like a clipping rectangle—anything within the border becomes the publisher. Figure 1-23 shows a publisher that contains clipped graphics and its subscriber in another application.
A user can create publishers and subscribers that overlap each other. Thus, borders may overlap and it may no longer be possible to turn on a particular border when the user clicks within a publisher. Drawing applications should provide a menu command, Show Borders, that toggles to Hide Borders. This command should allow users to turn all publisher and subscriber borders on or off.
A publisher and subscriber with clipped graphics
Bitmapped Graphics Borders
Creating a border around bitmapped graphics in applications is similar to doing so in object-oriented drawing applications. The border appears around the selected area. The user can create overlapping publishers and subscribers in bitmapped graphics applications. You need to provide a Show/Hide Borders command to allow users to turn all borders on and off.
Duplicating Publishers and Subscribers
Whenever a user clicks a publisher or subscriber border, you should change the contents of the section to a selected state. You should discourage users from making multiple copies of a publisher and pasting them in the same or other documents, because the contents of the edition would be difficult or impossible to predict. Multiple copies of the same publisher also contain the same control block value. See “Creating and Registering a Section” later in this chapter for detailed information on control blocks.
When a user attempts to create a copy of a publisher that already exists, you should display an alert box such as the one shown in Figure 1-24.
Creating multiple publishers alert box
When a user attempts to save a document that contains multiple copies of the same publisher, display an alert box such as the one shown in Figure 1-25.
Saving multiple publishers alert box
If a user decides to ignore your alert box, your application should still save the document, but you should continue to display this error message every time the user saves this document.
A user can modify the contents of any duplicate publisher, but the contents of the edition will be whichever publisher was the last to write.
When a user chooses to copy and paste or duplicate a section, use the HandToHand function (described in the Operating System Utilities chapter in Volume II) to duplicate the section record and alias record. Put the alias field of the cloned section record with the handle to the cloned alias record and generate a unique section identification number for it. In addition, you should also place the section data, section record, and alias record in the scrap.
Use the RegisterSection function (described earlier in “Opening and Closing a Document Containing Sections”) to register the cloned section’s section record.
A user can select the contents of a publisher without selecting the border and copy just the data to a new location. In this case, the user has simply copied data (and not the publisher). Do not create a border for this data in the new location.
Modifying a Subscriber
When the user selects data or clicks in the data area of a subscriber, you should highlight the entire contents of the subscriber using reverse video. You can allow users to globally adorn subscribers. For example, a user might select a subscriber within a document and change all text from plain to bold. However, you should discourage users from modifying the individual elements contained within a subscriber—for example, by editing a sentence or rotating an individual graphical object.
Remember that each time a new edition arrives for a subscriber, any modifications that the user has introduced are overwritten. Global adornment of a subscriber is much easier for your application to regenerate.
If you do allow a user to edit a subscriber section, provide an enable/disable editing option within the subscriber options dialog box using the SectionOptionsExpDialog function, described later in “Customizing Dialog Boxes.” When you allow a user to edit a subscriber, you should change the subscriber from a selected state to editable data.
In addition to global adornment, your application may also need to support partial selection of subscribers to enable spell checking and search operations.
Because a user can modify a publisher just like any other portion of a document, its subscriber may change in size as well as content. For example, a user may modify a publisher by adding two additional columns to a spreadsheet.
Relocating an Edition
In the Finder, users cannot move an edition across volumes. To relocate an edition, the user must first select its publisher and cancel the section (remember to remove the border). The user needs to republish and then select a new volume location for the edition. As a convenience for the user, you should retain the selection of all the publisher data after the user cancels the section to make it easy to republish the section.
Customizing Dialog Boxes
The expandable dialog box functions allow you to add items to the bottom of the dialog boxes, apply alternate mapping of events to item hits, apply alternate meanings to the item hits, and choose the location of the dialog boxes. See the Dialog Manager chapter in Volume I and the Standard File Package chapters in Volumes I and VI for additional information.
The expandable versions of these dialog boxes require five additional parameters. Use the NewPublisherExpDialog function to expand the publisher dialog box.
The reply parameter is a pointer to a NewPublisherReply, NewSubscriberReply, or SectionOptionsReply record, respectively.
You can automatically center the dialog box by passing (–1, –1) in the where parameter.
The expansionDITLresID parameter should be 0 or a valid dialog item list ('DITL') resource ID. This integer is the ID of a dialog item list whose items are appended to the end of the standard dialog item list. The dialog items keep their relative positions, but they are moved as a group to the bottom of the dialog box. See the Dialog Manager chapter in Volume I for additional information on dialog item lists.
The filterProc parameter should be a valid, expandable modal filter procedure pointer or NIL. This procedure is called by the ModalDialog function. The filterProc function enables you to map real events (such as a mouse-down event) to an item hit (such as clicking the Cancel button). For instance, you may want to map a keyboard equivalent to an item hit. See the Dialog Manager chapter in Volume I for information on the ModalDialog function.
The dlgHook parameter should be a valid, expandable dialog hook procedure pointer or NIL. This procedure is called after each call to the ModalDialog filter function. The dlgHook parameter takes the appropriate action, such as filling in a check box. The itemOffset parameter to the procedure is the number of items in the dialog item list before the expansion dialog items. You need to subtract the item offset from the item hit to get the relative item number in the expansion dialog item list. The return value from the dlgHook parameter is the absolute item number.
When the Edition Manager displays subsidiary dialog boxes in front of another dialog box on the user’s screen, your dlgHook and filterProc parameters should check the refCon field in the WindowRecord data type (from the window field in the DialogRecord) to determine which window is currently in the foreground. The main dialog box for the NewPublisherExpDialog and the NewSubscriberExpDialog functions contains the following constant:
CONST sfMainDialogRefCon = 'stdf'; {new publisher and }
{ new subscriber}
The main dialog box for the SectionOptionsExpDialog function contains the following constant:
See “Summary of the Edition Manager” later in this chapter for additional constants.
The yourDataPtr parameter is reserved for your use. It is passed back to your hook and modal filter procedure. This parameter does not have to be of type Ptr—it can be any 32-bit quantity that you want. In Pascal, you can pass in register A6 for yourDataPtr, and make dlgHook and filterProc local functions without the last parameter. The stack frame is set up properly for these functions to access their parent local variables. See the Standard File Package chapter in this volume for detailed information.
For the NewPublisherExpDialog and NewSubscriberExpDialog functions, all the pseudo-items for the Standard File Package—such as sfHookFirstCall(–1), sfHookNullEvent(100), sfHookRebuildList(101), and sfHookLastCall(–2)—can be used, as well as emHookRedrawPreview(150).
For the SectionOptionsExpDialog function, the only valid pseudo-items are sfHookFirstCall(–1), sfHookNullEvent(100), sfHookLastCall(–2), emHookRedrawPreview(150), emHookCancelSection(160), emHookGoToPublisher(161), emHookGetEditionNow(162), emHookSendEditionNow(162), emHookManualUpdateMode(163), and emHookAutoUpdateMode(164). See the Standard File Package chapter in this volume for information on pseudo-items.
1The Edition Manager
Subscribing To Non-Edition Files
Using the Edition Manager, a subscriber can read data directly from another document, such as an entire 'PICT' file, instead of subscribing to an edition. This feature is for advanced applications that can set up bottleneck procedures for reading. Figure 1-26 shows a document that is subscribing directly to a 'PICT' file.
For each application, the Edition Manager keeps a pointer to a bottleneck function. The Edition Manager never opens or closes an edition container directly. Instead, the Edition Manager calls the current edition opener. The InitEditionPack function (described later in “Initializing the Edition Manager”) sets up the current system opener function.
To override the standard opener function, create an opener function that contains the following parameters.
FUNCTION MyOpener (selector: EditionOpenerVerb;
VAR PB: EditionOpenerParamBlock) : OSErr;
Subscribing directly to a 'PICT' file
Your opener needs to know which formats the file contains and how the data is supposed to be read or written.
The opener can allocate a handle or pointer to contain information such as file reference numbers. This value is passed as ioRefNum to the I/O procedures.
The eoOpen and eoOpenNew edition opener verbs (described later in “Calling an Edition Opener Procedure”) return a pointer to a function to do the actual reading and writing.
The following sections describe
n how to get the current edition opener procedure
n how to set your own edition opener procedure
n how to call an edition opener procedure
n the edition opener parameters
Getting the Current Edition Opener
When you want to get the current edition opener procedure, use the GetEditionOpenerProc function.
err := GetEditionOpenerProc (opener);
The opener parameter returns the pointer to the current edition opener procedure. A different current opener is kept for each application. One application’s opener is never called by another application.
Setting an Edition Opener
You can provide your own edition opener procedure. To do so, use the SetEditionOpenerProc function.
err := SetEditionOpenerProc (@MyOpener);
The @MyOpener parameter is a pointer to the edition opener procedure that you are providing. If you set the current opener to be a routine in your own code, be sure to call the GetEditionOpenerProc function first so that you can save the previous opener. If your opener is passed a selector that it does not understand, use the previous opener provided by the Edition Manager to handle it. See the next section for a list of selectors.
Calling an Edition Opener Procedure
You use the CallEditionOpenerProc function to call an edition opener procedure. Since the Edition Manager is a package that may move, a real pointer cannot be safely returned for the standard opener and I/O procedures. The system opener and the I/O routines are returned as a value that is not a valid address to a procedure. The CallEditionOpenerProc and CallFormatIOProc functions check for these values and call the system procedures.
You should never assume that a value for a system procedure is a fixed constant.
Each time the Edition Manager opens or closes an edition container, it calls the current edition opener procedure and passes it an opener verb and a parameter block.
Your opener must be careful when closing documents since a document may already have been opened by another application. Be sure to use the Open/Deny modes whenever possible. Do not close a document if it was already open when your application opened it.
Listing Files That Can Be Subscribed To
The NewSubscriberDialog function calls the eoCanSubscribe opener verb to build the list of files that can be subscribed to. The preview in the subscriber dialog box is generated by calling the GetStandardFormats function (described in “Edition Container Formats” later in this chapter), which calls the format I/O verbs eoOpen, ioHasFormat, ioRead, and then eoClose. See “Calling a Format I/O Procedure” later in this chapter for detailed information on format I/O verbs.
Reading From and Writing to Files
The I/O procedure is a routine that actually reads and writes the data. It too has an interface of a selector and a parameter block.
To override the standard reading and writing functions, create an I/O function. Note that you also need to provide your own opener function to call your I/O function. See “Calling an Edition Opener Procedure” earlier in this chapter.
FUNCTION MyIO (selector: FormatIOVerb;
VAR PB: FormatIOParamBlock) : OSErr;
Calling a Format I/O Procedure
To indicate to the Edition Manager which format I/O procedure to use, use the CallFormatIOProc function.
err := CallFormatIOProc (selector, PB, routine);
Set the selector parameter to one of the format I/O verbs. The format I/O verbs include
n ioHasFormat
n ioReadFormat
n ioNewFormat
n ioWriteFormat
The PB parameter of the CallFormatIOProc function contains a format I/O parameter block.
The routine parameter of the CallFormatIOProc function is a pointer to a format I/O procedure.
The following list shows which fields of FormatIOParamBlock are used by the format I/O verbs.
Opener
verb Parameter Description Called by
ioHasFormat Æ ioRefNum I/O reference number returned EditionHasFormat,
by opener. GetStandardFormats,
Æ format Check for this format. and ReadEdition
¨ formatIndex An optional enumeration of the functions
supplied format.
¨ buffLen If found, return the length size or –1
if size is unknown.
¨ Return value A noErr or noTypeErr code.
ioReadFormat Æ ioRefNum I/O reference number returned by ReadEdition and
opener. GetStandardFormats
Æ format Get this format. functions
Æ formatIndex Value returned by ioHasFormat.
Æ offset Read format beginning from this offset.
Æ buffPtr Put data beginning here.
´ buffLen Specify buffer length to read, and return
actual amount received.
¨ Return value A noErr code, or appropriate error code.
ioNewFormat Æ ioRefNum I/O reference number returned by SetEditionFormatMark
opener. and WriteEdition
Æ format Create this format. functions
¨ formatIndex An optional enumeration of the
supplied format.
¨ Return value A noErr code, or appropriate error code.
ioWriteFormat Æ ioRefNum I/O reference number returned by WriteEdition function
opener.
Æ format Get this format.
Æ formatIndex Value returned by ioNewFormat.
Æ offset Write format beginning from this offset.
Æ buffPtr Get data beginning here.
´ buffLen Specify buffer length to write.
¨ Return value A noErr code or appropriate error code.
The marks for each format are kept by the Edition Manager. The format I/O procedure only needs to be able to read or write, beginning at any offset. If you know that your application always reads an entire format sequentially, you can ignore the offset.
Reference to the Edition Manager
This section describes the routines for
n initializing the Edition Manager
n creating and registering a section
n creating and deleting an edition container
n setting and locating a format mark
n reading in edition data
n writing out edition data
n closing an edition after reading or writing
n displaying dialog boxes
n locating a publisher and edition from a subscriber
n reading edition container formats
n reading and writing non-edition files
Result codes appear at the end of each function where applicable. In addition to the specific result codes listed, you may receive errors generated by the Alias Manager, File Manager, and Memory Manager.
Routines
This section describes the routines you use to
n initialize the Edition Manager
n create and register a section
n create and delete an edition container
n set and locate a format mark
n read in edition data
n write out edition data
n close an edition after reading or writing
n display dialog boxes
n locate a publisher and edition from a subscriber
n read and write non-edition files
Initializing the Edition Manager
You use the InitEditionPack function to initialize the Edition Manager. Note that you should only call this function once.
1InitEditionPack
Before calling the InitEditionPack function, be sure to determine whether the Edition Manager is available on your system by using the Gestalt function. The Gestalt selector is gestaltEditionMgrAttr ('edtn').
FUNCTION InitEditionPack : OSErr;
DESCRIPTION
The InitEditionPack function returns an error if the package could not be loaded into the system heap and properly initialized. In addition, you may also receive resource errors.
RESULT CODES
noErr 0 No error
memFullErr –108 Could not load package
Creating and Registering a Section
You use the NewSection function to create a new section (either publisher or subscriber) and alias record (which is a reference to the edition container from the document containing the publisher or subscriber section).
The NewSection function registers a section similar to the way that the RegisterSection function informs the Edition Manager about a section (except that the NewSection function does not resolve an alias to find the edition container).
When a section needs to be disposed of because the document containing the section is closing, or the user has canceled the section, you need to call the UnRegisterSection function before disposing of the section.
Using the IsRegisteredSection function, your application must verify that each event received is for a registered section. This is necessary because your application may have just called UnRegisterSection while the event was already being held in the event queue.
If a user saves a document that contains sections under another name (using Save As) or pastes a portion of a document that contains a section into another document, use the AssociateSection function to update the section’s alias record.
1NewSection
The NewSection function allocates two handles in the current zone: one handle for the section record and another handle for the alias record. Note that you are responsible for unregistering handles created by the Edition Manager.
FUNCTION NewSection (container: EditionContainerSpec;
sectionDocument: FSSpecPtr;
kind: SectionType; sectionID: LongInt;
initialMode: UpdateMode;
VAR sectionH: SectionHandle) : OSErr;
container The container parameter specifies the edition you want to publish or subscribe to.
sectionDocument
The sectionDocument parameter contains the volume reference number, directory ID, and filename of the document that contains a section. The sectionDocument parameter can be NIL if your current document has never been saved. If so, when the user finally saves the document, remember to call the AssociateSection function on each section to update its alias record.
kind The kind parameter designates the type of section (publisher or subscriber) being created.
sectionID A section ID is a unique number for a section within a document. The sectionID parameter initializes the sectionID field within the new section record. Do not use 0 or –1 for an ID number; these numbers are reserved. If your application copies a section, you need to specify a unique number for the copied section.
initialMode
The initialMode parameter contains the update mode for the section. For publishers this is either the pumOnSave or pumManual constant, and for subscribers it is either sumAutomatic or sumManual. A subscriber created with sumAutomatic mode automatically receives a Section Read event. To prevent this initial Section Read event, you should set the initialMode parameter to sumManual and then, when NewSection returns, set the mode field of the section record to sumAutomatic.
sectionH If the NewSection function fails, the sectionH parameter is set to NIL. If the function is successful, sectionH contains the handle to the allocated section record.
DESCRIPTION
Your application receives the multiplePublisherWrn result code if there is another registered publisher to the same edition. Your application receives the notThePublisherWrn result code if another publisher (to the same edition) was the last section to write to the edition. The multiplePublisherWrn result code takes priority over the notThePublisherWrn result code.
In addition, you may also receive memory and file opening errors.
RESULT CODES
noErr 0 No error
editionMgrInitErr –450 Manager not initialized
badSectionErr –451 Not a valid section type
badSubPartErr –454 Bad edition container spec
multiplePublisherWrn –460 Already is a publisher
notThePublisherWrn –463 Not the publisher
1RegisterSection
The RegisterSection function adds the section record to the Edition Manager’s list of registered sections and tries to allocate a control block. After calling the RegisterSection function, the controlBlock field of the section record is either NIL or a valid control block.
FUNCTION RegisterSection (sectionDocument: FSSpec;
sectionH:SectionHandle;
VAR aliasWasUpdated: Boolean) : OSErr;
sectionDocument
The sectionDocument parameter contains the volume reference number, directory ID, and filename of the document that contains a section.
sectionH The sectionH parameter is a handle to the section record for a given section.
aliasWasUpdated
The aliasWasUpdated parameter returns TRUE if the alias for the edition container subscribed to was out of date and was updated. This may occur if the edition file was moved to a new location or was renamed.
DESCRIPTION
For a subscriber, the control block is NIL if the RegisterSection function could not locate the edition container being subscribed to. The RegisterSection function then returns either the containerNotFoundWrn or the userCanceledErr result code. For a publisher, if the RegisterSection function could not locate its corresponding edition container, the Edition Manager creates an edition container in the last place the edition was located and creates a control block for it. If the RegisterSection function could not locate a publisher’s corre-sponding edition container or its volume, the control block is NIL. You should never re-register a section that is already registered.
Note that you can compare control blocks for individual sections. If two sections contain the same control block value, these sections publish or subscribe to the same edition (unless the control block is NIL). The Edition Manager keeps track of how many sections are referencing a control block to know when it can be deallocated. The control block maintains a count of how many sections are referencing it. Each time you use the UnRegisterSection function, the control block subtracts one from the number of sections. When the number of sections reaches 0, the control block is deallocated.
Your application receives the multiplePublisherWrn result code if there is another registered publisher to the same edition. Your application receives the notThePublisherWrn result code if another publisher (to the same edition) was the last section to write to the edition. The multiplePublisherWrn result code takes priority over the notThePublisherWrn result code.
In addition, you may also receive memory and file opening errors.
RESULT CODES
noErr 0 No error
userCanceledErr –128 User chose Cancel from a mount server dialog
box
editionMgrInitErr –450 Manager not initialized
badSectionErr –451 Not valid section type
multiplePublisherWrn –460 Already is a publisher
containerNotFoundWrn –461 Alias was not resolved
notThePublisherWrn –463 Not the publisher
1UnRegisterSection
When a section needs to be disposed of because the document containing the section is closing, or the user has canceled the section, you need to call the UnRegisterSection function before disposing of the section.
FUNCTION UnRegisterSection (sectionH: SectionHandle) : OSErr;
sectionH The sectionH parameter is a handle to the section record for a given section.
DESCRIPTION
The UnRegisterSection function removes the section from the Edition Manager’s list of registered sections. You can then dispose of the section record and alias record with standard Memory and Resource Manager calls. Once unregistered, a section does not receive any events and cannot read or write any data. Depending on your Clipboard strategy, you may want to unregister sections that have been cut into the Clipboard.
RESULT CODES
noErr 0 No error
fBsyErr –47 Section doing I/O
editionMgrInitErr –450 Manager not initialized
notRegisteredSectionErr –452 Not registered
1IsRegisteredSection
Using the IsRegisteredSection function, your application must verify that each event received is for a registered section. This is necessary because your application may have just called UnRegisterSection while the event was already being held in the event queue.
FUNCTION IsRegisteredSection (sectionH: SectionHandle) : OSErr;
sectionH The sectionH parameter is a handle to the section record for a given section.
DESCRIPTION
The IsRegisteredSection function does not return a Boolean—a noErr result code indicates that a section is registered.
RESULT CODES
noErr 0 No error
notRegisteredSectionErr –452 Not registered
1AssociateSection
If a user saves a document that contains sections under another name (using Save As) or pastes a portion of a document that contains a section into another document, use the AssociateSection function to update the section’s alias record.
FUNCTION AssociateSection (sectionH: SectionHandle;
newSectionDocument: FSSpecPtr) : OSErr;
sectionH The sectionH parameter is a handle to the section record for a given section.
newSectionDocument
The newSectionDocument parameter contains the volume reference number, directory ID, and filename of the new document.
DESCRIPTION
The AssociateSection function calls UpdateAlias on the section’s alias record.
In addition, you may also receive update alias errors.
RESULT CODE
noErr 0 No error
Creating and Deleting an Edition Container
Each time a user creates a new publisher section within a document to an edition that does not already exist, you use the CreateEditionContainerFile function to create an empty edition container.
To remove the edition container, use the DeleteEditionContainerFile function.
1CreateEditionContainerFile
You use the CreateEditionContainerFile function to create an empty edition container.
FUNCTION CreateEditionContainerFile
(editionFile: FSSpec; fdCreator: OSType;
editionFileNameScript: ScriptCode) : OSErr;
editionFile
The editionFile parameter contains the volume reference number, directory ID, and filename for the edition container being created.
fdCreator The fdCreator parameter contains the creator type for the edition.
editionFileNameScript
The editionFileNameScript parameter is the script of the filename. It is returned in the theFileScript field of the edition container specification record. (The new publisher reply record includes a container field for an edition container specification record.)
DESCRIPTION
The CreateEditionContainerFile function creates an empty edition container file (it does not contain any formats). This function creates a file type 'edtu'. As soon as you write data to the edition, the type is updated (to 'edtp' for graphics, 'edtt' for text, or 'edts' for sound). If both text and pict are written, the type that was written first determines the file type. If your application has a bundle, you should designate an icon for the appropriate edition types that you can write.
In addition, you may also receive file creating errors.
RESULT CODE
noErr 0 No error
editionMgrInitErr –450 Manager not initialized
1DeleteEditionContainerFile
If a user cancels a publisher section within a document or closes a document containing a newly created publisher without saving, you need to remove the edition container.
To locate the appropriate edition container to be deleted, use the GetEditionInfo function. You use the UnRegisterSection function (only after using the GetEditionInfo function) to unregister the section record and alias record of the publisher being canceled. See “Locating a Publisher and Edition From a Subscriber” later in this chapter for detailed information on the GetEditionInfo function. See “Creating and Registering a Section” earlier in this chapter for detailed information on the UnRegisterSection function.
To remove the edition container, use the DeleteEditionContainerFile function.
FUNCTION DeleteEditionContainerFile (editionFile: FSSpec) : OSErr;
editionFile
The editionFile parameter contains the volume reference number, directory ID, and filename for the edition container being deleted.
DESCRIPTION
If the user cancels a publisher, do not call the DeleteEditionContainerFile function until the user saves the document. This allows the user to undo changes and revert to the last saved version of the document.
The DeleteEditionContainerFile function only deletes the edition container if there is no registered publisher. You need to unregister a publisher before you can delete its corresponding edition container.
You should use the DeleteEditionContainerFile function even if there are subscribers to the edition. When a subscriber section tries to read in data, it receives an error.
In addition, you may also receive file deleting errors.
RESULT CODES
noErr 0 No error
editionMgrInitErr –450 Manager not initialized
Setting and Locating a Format Mark
Use the SetEditionFormatMark function to set the current mark for a section format and use the GetEditionFormat Mark function to locate the current marker for a particular format.
1SetEditionFormatMark
A format mark indicates the next position of a read or write operation. Initially, a mark defaults to 0. After reading or writing data, the format mark is set past the last position written to or read from.
FUNCTION SetEditionFormatMark (whichEdition: EditionRefNum;
whichFormat: FormatType;
setMarkTo: LongInt) : OSErr;
whichEdition
The whichEdition parameter is the reference number for the edition.
whichFormat
The whichFormat parameter indicates the format type for the edition.
setMarkTo The setMarkTo parameter is the offset for the next read or write for this format.
RESULT CODES
noErr 0 No error
rfNumErr –51 Bad edition reference number
noTypeErr –102 Unknown format (subscriber only)
editionMgrInitErr –450 Manager not initialized
1GetEditionFormatMark
Use the GetEditionFormat Mark function to locate the current marker for a particular format.
FUNCTION GetEditionFormatMark (whichEdition: EditionRefNum;
whichFormat: FormatType;
VAR currentMark: LongInt) : OSErr;
whichEdition
The whichEdition parameter is the reference number for the edition.
whichFormat
The whichFormat parameter indicates the format type for the edition.
currentMark
The currentMark parameter is the mark for the format.
DESCRIPTION
If the edition does not support the format specified in the whichFormat parameter, you receive a noTypeErr result code.
RESULT CODES
noErr 0 No error
rfNumErr –51 Bad edition reference number
noTypeErr –102 Unknown format
editionMgrInitErr –450 Manager not initialized
Reading in Edition Data
To initiate the reading of data from an edition (for a subscriber), use the OpenEdition function.
Use the EditionHasFormat function to learn in which formats the edition data is available.
You use the ReadEdition function to read data from an edition. This function reads from the current mark for the specified format.
1OpenEdition
To initiate the reading of data from an edition (for a subscriber), use the OpenEdition function.
FUNCTION OpenEdition (subscriberSectionH: SectionHandle; VAR
refNum: EditionRefNum) : OSErr;
subscriberSectionH
The subscriberSectionH parameter is a handle to the section record for a given section.
refNum The refNum parameter returns the reference number for the edition.
DESCRIPTION
Multiple subscribers can each call the OpenEdition function simultaneously (each call returns a different reference number) and read data from a single edition. If a publisher (located on a different machine) is writing to an edition when you use the OpenEdition function, you receive an flLckedErr result code.
In addition, you may also receive memory, file opening, and file reading errors.
RESULT CODES
noErr 0 No error
flLckedErr –45 Publisher writing to an edition
permErr –54 Not a subscriber
editionMgrInitErr –450 Manager not initialized
1EditionHasFormat
Use the EditionHasFormat function to learn in which formats the edition data is available.
FUNCTION EditionHasFormat (whichEdition: EditionRefNum;
whichFormat:FormatType;
VAR formatSize: Size) : OSErr;
whichEdition
The whichEdition parameter is the reference number for the edition.
whichFormat
The whichFormat parameter indicates the format type that you are requesting. For the whichFormat parameter, you should decide which formats to read in the same way that you do when using paste from the Scrap Manager. You can also get a list of all the available formats and their respective lengths by reading the kFormatListFormat ('fmts') format.
formatSize The formatSize parameter specifies the format length.
DESCRIPTION
If the requested format is available, this function returns noErr, and the formatSize parameter returns the size of the data in the specified format or kFormatLengthUnknown (–1), which signifies that the size is unknown. You should therefore continue to read the format until there is no more data.
Be aware that the EditionHasFormat function may return kFormatLengthUnknown for the length of the format.
RESULT CODES
noErr 0 No error
rfNumErr –51 Bad edition reference number
noTypeErr –102 Format not available
editionMgrInitErr –450 Manager not initialized
1ReadEdition
Use the ReadEdition function to read data from an edition. This function reads from the current mark for the specified format.
FUNCTION ReadEdition (whichEdition: EditionRefNum;
whichFormat: FormatType; buffPtr: UNIV Ptr;
VAR buffLen: Size) : OSErr;
whichEdition
The whichEdition parameter is the reference number for the edition.
whichFormat
The whichFormat parameter indicates the format type that you want to read.
buffPtr The buffPtr parameter is a pointer to the buffer into which you want to read the data.
buffLen The buffLen parameter is the number of bytes that you want to read into the buffer.
DESCRIPTION
The buffLen parameter is also a return value that returns the total number of bytes read into the buffer. If the buffLen parameter returns a value smaller than the value you have specified, there is no additional data to read, and the ReadEdition function returns a noErr result code. If you use the ReadEdition function after all data is read in, the ReadEdition function returns an eofErr result code.
You can read data from an edition while a publisher on the same machine is writing data to the same edition. The data that you are reading is the old edition (not the data that the publisher is writing). If the publisher finishes writing data before you are through reading the old edition data, the ReadEdition function returns an abortErr result code. If the ReadEdition function returns an abortErr result code, you should stop trying to read data and use the CloseEdition function with the successful parameter set to FALSE.
In addition, you may also receive file reading errors.
RESULT CODES
noErr 0 No error
abortErr –27 Publisher has written a new edition
eofErr –39 No more data of that format
rfNumErr –51 Bad edition reference number
noTypeErr –102 Format not available
editionMgrInitErr –450 Manager not initialized
Writing out Edition Data
To initiate the writing of data from a publisher to its edition container, use the OpenNewEdition function.
Use the WriteEdition function to write data to an edition.
1OpenNewEdition
To initiate the writing of data from a publisher to its edition container, use the OpenNewEdition function.
FUNCTION OpenNewEdition (publisherSectionH: SectionHandle;
fdCreator:OSType;
publisherSectionDocument: FSSpecPtr;
VAR refNum: EditionRefNum) : OSErr;
publisherSectionH
The publisherSectionH parameter is the publisher section that is writing to the edition.
fdCreator The fdCreator parameter is the Finder creator type of the new edition icon.
publisherSectionDocument
The publisherSectionDocument parameter is the document that contains the publisher. This parameter is used to create an alias from the edition to the publisher’s document. If you pass NIL for publisherSectionDocument, an alias is not made in the edition file.
refNum The refNum parameter returns the reference number for the edition. This parameter is necessary for subsequent calls to WriteEdition, SetEditionFormatMark, and CloseEdition to specify which publisher is writing its data to an edition. If the edition cannot be opened for writing because there is another publisher writing to it, or because the file system does not allow writing, an error is returned and refNum is set to NIL.
DESCRIPTION
The OpenNewEdition function returns an flLckdErr result code if there is a subscriber on another machine reading data from the same edition. The OpenNewEdition function returns a permErr result code if there is a registered publisher to that edition on another machine.
The Edition Manager allows two registered publishers that are located on the same machine to write to the same edition. Note that multiple publishers cannot write to the same edition simultaneously—only one publisher can write to an edition at a given time.
In addition, you may also receive file creating, file opening, file reading, resolve alias, and memory errors.
RESULT CODES
noErr 0 No error
flLckdErr –45 Edition in use by another section
permErr –54 Registered publisher on another machine
wrPermErr –61 Not a publisher
editionMgrInitErr –450 Manager not initialized
1WriteEdition
Use the WriteEdition function to write data to an edition. This function begins writing at the current mark for the specified format.
FUNCTION WriteEdition (whichEdition: EditionRefNum;
whichFormat: FormatType;
buffPtr: UNIV Ptr; buffLen: Size) : OSErr;
whichEdition
The whichEdition parameter is the reference number for the edition.
whichFormat
The whichFormat parameter indicates the format type that you want to write.
buffPtr The buffPtr parameter is a pointer to the buffer that you are writing into the edition.
buffLen The buffLen parameter is the number of bytes that you want to write. If the data cannot be entirely written to the edition, the WriteEdition function returns an error.
DESCRIPTION
In addition, you may also receive file writing and memory errors.
RESULT CODES
noErr 0 No error
rfNumErr –51 Bad edition reference number
editionMgrInitErr –450 Manager not initialized
Closing an Edition After Reading or Writing
After finishing reading from or writing to an edition, use the CloseEdition function to close the edition.
1CloseEdition
Use the CloseEdition function to close the edition after you finish reading from or writing to an edition.
FUNCTION CloseEdition (whichEdition: EditionRefNum;
successful: Boolean) : OSErr;
whichEdition
The whichEdition parameter is the reference number for the edition.
successful The successful parameter indicates whether your application was successful in reading or writing data to the edition.
DESCRIPTION
When a subscriber successfully finishes reading data from the edition, the CloseEdition function takes the modification date of the edition file that you have read and puts it in the mdDate field of the subscriber’s section record. This indicates that the data contained in the edition and the subscriber section within the document are the same.
When a subscriber is unsuccessful in reading data from an edition (because there is not enough memory, or you didn’t find a format that you can read), set the successful parameter to FALSE. The CloseEdition function then closes the edition, but does not set the mdDate field. This implies that the subscriber is not updated with the latest edition.
When a publisher successfully finishes writing data to an edition, the CloseEdition function makes the data that the publisher has written to the edition available to any subscribers and sets the corresponding edition file’s modification date (ioFlMdDat) to the mdDate field of the publisher’s section record. The Edition Manager then sends a Section Read event to all current subscribers set to automatic update mode. At this point, the file type of the edition file is set based on the first known format that the publisher wrote.
When a publisher is unsuccessful in writing data to an edition, the CloseEdition function discards what the publisher has written to the edition. The data contained in the edition prior to writing remains unchanged, and Section Read events are not sent to subscribers.
In addition, you may also receive file closing errors.
RESULT CODES
noErr 0 No error
rfNumErr –51 Bad edition reference number
editionMgrInitErr –450 Manager not initialized
Displaying Dialog Boxes
The Edition Manager supports three dialog boxes: publisher, subscriber, and options dialog boxes. Your application can display simple dialog boxes that appear centered on the user’s screen, or you can customize your dialog boxes.
Use the GetLastEditionContainerUsed function to get the default edition to display.
Use the NewSubscriberDialog function to display the subscriber dialog box on the user’s screen and use the NewPublisherDialog function to display the publisher dialog box on the user’s screen. Unlike the Standard File routines, the NewPublisherDialog and the NewSubscriberDialog functions allow you to specify the initial volume reference number and directory ID so that there can be one default location for editions for all applications.
You use the SectionOptionsDialog function to display the publisher options and subscriber options dialog boxes on the user’s screen.
The NewSubscriberExpDialog, NewPublisherExpDialog, and SectionOptionsExpDialog functions are the same as the simple dialog functions but have five additional parameters.
1GetLastEditionContainerUsed
Use the GetLastEditionContainerUsed function to get the default edition to display. This function allows a user to easily subscribe to the data recently published.
FUNCTION GetLastEditionContainerUsed
(VAR container: EditionContainerSpec) : OSErr;
container If the GetLastEditionContainer function locates the last edition for which a section was created, the container parameter contains its volume reference number, directory ID, filename, and part, and returns a noErr result code. (The last edition created is associated with the last time that your application or another application located on the same machine used the NewSection function.)
DESCRIPTION
If the last edition used is missing, the GetLastEditionContainerUsed function returns an fnfErr result code, but still returns the correct volume reference number and directory ID that you should use for the NewSubscriberDialog function.
Pass the information from the GetLastEditionContainerUsed function to the NewSubscriberDialog function.
RESULT CODES
noErr 0 No error
fnfErr –43 Edition container not found
editionMgrInitErr –450 Manager not initialized
1NewSubscriberDialog
Use the NewSubscriberDialog function to display the subscriber dialog box on the user’s screen.
FUNCTION NewSubscriberDialog
(VAR reply: NewSubscriberReply) : OSErr;
reply The reply parameter contains the new subscriber reply record.
canceled If the NewSubscriberDialog function returns with the canceled field set to TRUE, the user canceled the dialog box. Otherwise, this field is FALSE and the container field holds the edition container for the new subscriber.
formatsMask The formatsMask field indicates which edition format type (text, graphics, and sound) to display within the subscriber dialog box. You can set the formatsMask field to the following constants: kTEXTformatMask (1), kPICTformatMask (2), or ksndFormatMask (4). To support a combination of formats, add the constants together. For example, a formatsMask of 3 displays both graphics and text edition format types in the subscriber dialog box.
container If the canceled field is FALSE, the container field holds the edition container for the new subscriber.
DESCRIPTION
The NewSubscriberDialog function (which is based on the CustomGetFile procedure described in the Standard File Package chapter in this volume) switches to the volume refer-ence number and directory ID and selects the filename of the edition container that you passed in. Use the GetLastEditionContainerUsed function to set the edition container to the last edition that was either published or subscribed to. This allows the user to publish and then easily subscribe.
Note that if an edition does not contain either 'PICT', 'TEXT', or 'snd ' data, it will not be seen by the NewSubscriberDialog function (unless you install an opener that adds it using eoCanSubscribe).
RESULT CODES
noErr 0 No error
editionMgrInitErr –450 Package not initialized
badSubPartErr –454 Bad edition container spec
1NewPublisherDialog
Use the NewPublisherDialog function to display the publisher dialog box on the user’s screen.
FUNCTION NewPublisherDialog
(VAR reply: NewPublisherReply) : OSErr;
reply The reply parameter contains a new publisher reply record.
TYPE NewPublisherReply =
RECORD
canceled: Boolean; {user canceled dialog box}
replacing: Boolean; {user chose existing }
{ filename for an edition}
usePart: Boolean; {always false in version 7.0}
preview: Handle; {handle to 'prvw', 'PICT', }
{ 'TEXT', or 'snd' data}
previewFormat: FormatType; {type of preview}
container: EditionContainerSpec;
{edition chosen}
END;
Field descriptions
canceled Upon return of the NewPublisherDialog function, the canceled and replacing fields are set. If the canceled field is set to TRUE, the user canceled the dialog box. If the replacing field is TRUE, the user chose an existing filename from the list of available editions and confirmed this replacement.
replacing If the replacing field is TRUE, do not call the CreateEditionContainerFile function, which creates a new edition container.
usePart The usePart field must be set to FALSE before calling the NewPublisherDialog function.
preview Set the preview field to be a handle to 'prvw', 'PICT', 'TEXT', or 'snd ' data.
previewFormat
Set the previewFormat field to indicate which type of data the handle references.
container The container field contains the volume reference number, directory ID, and filename for the edition that the user selected.
DESCRIPTION
The NewPublisherDialog function (which is based on the CustomPutFile procedure described in the Standard File Package chapter) switches to the volume reference number and directory ID and sets the text edit field to the filename of the edition container that you passed in. Set the fileName field of the file system specification record to be the default name of the edition file. (The new publisher reply record includes a container field for an edition container specification record, and the edition container specification record includes a field [theFile] for a file system specification record.) See “Creating a Publisher” earlier in this chapter for information on the default file specification.
You should deallocate the handle referenced by the preview field to free up memory.
RESULT CODES
noErr 0 No error
editionMgrInitErr –450 Package not initialized
badSubPartErr –454 Bad edition container spec
1SectionOptionsDialog
Use the SectionOptionsDialog function to display the publisher options and subscriber options dialog boxes on the user’s screen.
FUNCTION SectionOptionsDialog
(VAR reply: SectionOptionsReply) : OSErr;
reply The reply parameter contains a section options reply record.
TYPE SectionOptionsReply =
RECORD
canceled: Boolean; {user canceled dialog box}
changed: Boolean; {changed the section record}
sectionH: SectionHandle; {handle to the specified }
{ section record}
action: ResType; {action codes}
END;
Field descriptions
canceled Upon return of the SectionOptionsDialog function, the canceled and changed fields are set. If the canceled parameter is set to TRUE, the user canceled the dialog box. Otherwise, this parameter is FALSE.
changed If the changed parameter is TRUE, the user changed the section record. For example, the update mode may have changed.
sectionH Set the sectionH parameter to the handle to the section record for the section the user selected.
action The action field contains the code for one of five user actions: action code is 'read' for user selection of the Get Edition Now button, action code is 'writ' for user selection of the Send Edition Now button, action code is 'goto' for user selection of the Open Publisher button, action code is 'cncl' for user selection of the Cancel Publisher or Cancel Subscriber button, action code is ' ' ($20202020) for user selection of the OK button
The NewSubscriberExpDialog, NewPublisherExpDialog, and SectionOptionsExpDialog functions are the same as the simple dialog functions but have five additional parameters. These additional parameters allow you to add items to the bottom of the dialog boxes, apply alternate mapping of events to item hits, apply alternate meanings to the item hits, and choose the location of the dialog boxes.
FUNCTION NewSubscriberExpDialog
(VAR reply: NewSubscriberReply; where:
Point;expansionDITLresID: Integer;
dlgHook: ExpDlgHookProcPtr; filterProc:
ExpModalFilterProcPtr;
yourDataPtr: UNIV Ptr) : OSErr;
FUNCTION NewPublisherExpDialog
(VAR reply: NewPublisherReply; where:
Point; expansionDITLresID: Integer;
dlgHook: ExpDlgHookProcPtr; filterProc:
ExpModalFilterProcPtr;
yourDataPtr: UNIV Ptr) : OSErr;
FUNCTION SectionOptionsExpDialog
(VAR reply: SectionOptionsReply; where:
Point; expansionDITLresID: Integer;
dlgHook: ExpDlgHookProcPtr;
filterProc: ExpModalFilterProcPtr;
yourDataPtr: UNIV Ptr) : OSErr;
reply The reply parameter contains a pointer from the new subscriber reply, new publisher reply, or the section options reply records.
where You can automatically center the dialog box by passing (–1, –1) in the where parameter.
expansionDITLresID
The expansionDITLresID parameter should be 0 or a valid dialog item list ('DITL') resource ID. This integer is the ID of a dialog item list whose items are appended to the end of the standard dialog item list. The dialog items keep their relative positions, but they are moved as a group to the bottom of the dialog box. See the Dialog Manager chapter in Volume I for additional information on dialog item lists.
dlgHook The dlgHook parameter should be a valid expandable dialog hook procedure pointer or NIL. This procedure is called after each call to the ModalDialog procedure. The dialog hook procedure takes the appropriate action, such as filling in a check box. The itemOffset parameter to the procedure is the number of items in the dialog item list before your expansion dialog items. You need to subtract the item offset from the item hit to get the relative item number in the expansion dialog item list. The return value from the dialog hook procedure is the absolute item number.
filterProc The filterProc parameter should be a valid expandable modal filter procedure pointer or NIL. This procedure is called by the ModalDialog procedure. This function allows you to map real events (such as a mouse-down event) to an item hit (such as clicking a Cancel button). For instance, you may want to map a keyboard equivalent to an item hit.
yourDataPtr
The yourDataPtr parameter is reserved for your use. It is passed back to your hook and modal-dialog filter function. This parameter does not have to be of type Ptr—it can be any 32-bit quantity that you want. In Pascal, you can pass in register A6 for yourDataPtr, and make dialog hook and filter procedure local functions without the last parameter. The stack frame is set up properly for these functions to access their parent local variables. See the Standard File Package chapter in this volume for detailed information.
DESCRIPTION
For the NewPublisherExpDialog and NewSubscriberExpDialog functions, all the pseudo-items for the Standard File Package such as hookFirstCall(–1), hookNullEvent(100), hookRebuildList(101), and hookLastCall(–2) can be used, as well as hookRedrawPreview(150).
For the SectionOptionsExpDialog function, the only valid pseudo-items are hookFirstCall(–1), hookNullEvent(100), hookLastCall(–2), emHookRedrawPreview(150), emHookCancelSection(160), emHookGoToPublisher(161), emHookGetEditionNow(162), emHookSendEditionNow(162), emHookManualUpdateMode(163), and emHookAutoUpdateMode(164).
If you have an expandable dialog hook function, it must contain the following parameters.
FUNCTION MyExpDlgHook (itemOffset: Integer; itemHit: Integer;
theDialog: DialogPtr;
yourDataPtr: Ptr) : Integer;
If you have an expandable modal-dialog filter function, it must contain the following parameters.
FUNCTION MyExpModalFilter (theDialog: DialogPtr;
VAR theEvent: EventRecord;
itemOffset: Integer;
VAR itemHit: Integer;
yourDataPtr: Ptr) : Boolean;
Locating a Publisher and Edition From a Subscriber
The GetEditionInfo function returns information about a section’s edition such as its location, last modification date, creator, and type.
Use the GetEditionInfo function to locate an edition container.
1GetEditionInfo
Use the GetEditionInfo function to obtain information about a section’s edition such as its location, last modification date, creator, and type.
FUNCTION GetEditionInfo
(sectionH: SectionHandle;
VAR editionInfo: EditionInfoRecord) : OSErr;
sectionH The sectionH parameter is a handle to the section record for a given section.
editionInfo
The editionInfo parameter contains an edition information record. The GetEditionInfo function returns the public information contained in the section’s control block.
DESCRIPTION
The Edition Manager synchronizes to ensure that the existing edition name corresponds to the Finder’s existing edition name. If the controlblock field of the section record is NIL, or the edition cannot be located, the GetEditionInfo function returns an fnfErr result code.
TYPE EditionInfoRecord =
RECORD
crDate: TimeStamp; {date edition container }
{ was created}
mdDate: TimeStamp; {date of last change}
fdCreator: OSType; {file creator}
fdType: OSType; {file type}
container: EditionContainerSpec; {the edition}
END;
crDate The crDate field contains the creation date of the edition.
mdDate The mdDate field contains the modification date of the edition.
fdCreator The fdCreator and fdType fields are the creator and type of the edition file.
fdType The fdCreator and fdType fields are the creator and type of the edition file.
container The container field includes a volume reference number, directory ID, filename, script, and part number for the edition.
RESULT CODES
noErr 0 No error
fnfErr –43 Not registered or file moved
editionMgrInitErr –450 Manager not initialized
1GoToPublisherSection
When the user wants to locate the publisher for a particular subscriber (by choosing Open Publisher in the subscriber options dialog box), the action code 'goto' is returned to you.
Use the GetEditionInfo function to find the edition container. You should next use the GoToPublisherSection function to open the document containing the publisher.
Use the GoToPublisherSection function to resolve the alias in the edition to find the document containing its publisher. In general, this function internally uses the GetStandardFormats function to get the alias to the publisher document and then resolves the alias. It next sends the Finder an Apple event to open the document (which launches its application if necessary) and, after the publisher is registered, sends a Section Scroll event to the publisher.
As an optimization, if there is a registered publisher, the GoToPublisherSection function simply sends a Section Scroll event to the publisher.
If the edition does not contain an alias and there are no registered publishers, then the GoToPublisherSection function sends an Open Documents event to open the edition to the creating application.
If the edition container is not an edition file (such as when you are using bottlenecks to subscribe to non-edition files), the GoToPublisherSection function sends the Finder an Apple event to open that file.
FUNCTION GoToPublisherSection
(container: EditionContainerSpec) : OSErr;
container The container parameter includes the edition volume reference number, directory ID, and filename. You obtain the edition container by calling the GetEditionInfo function.
DESCRIPTION
In addition, you may also receive resolve alias errors.
RESULT CODES
noErr 0 No error
editionMgrInitErr –450 Manager not initialized
badSubPartErr –454 Invalid edition container
Edition Container Formats
The Edition Manager calls the GetStandardFormats function to get the alias used in the GoToPublisherSection function and to get the preview shown in the subscriber dialog box. You probably do not need to call this function directly.
1GetStandardFormats
You probably do not need to call the GetStandardFormats function directly because the Edition Manager calls this function.
FUNCTION GetStandardFormats
(container: EditionContainerSpec;
VAR previewFormat: FormatType;
preview, publisherAlias, formats:Handle) : OSErr;
container The container parameter is a pointer to the edition volume reference number, directory ID, filename, and part.
previewFormat
The first format that was written returns in the preview handle and the previewFormat parameter is set to its type.
preview The preview parameter tries to find one of four formats: 'prvw', 'PICT', 'TEXT', or 'snd '.
publisherAlias
The publisherAlias parameter reads the format kPublisherDocAliasFormat ('alis').
formats The formats parameter reads the virtual format kFormatListFormat ('fmts').
DESCRIPTION
You should pass in valid handles for the formats that you want and NIL for the formats that you don’t want. The handles are resized to the size of the data.
If one of the requested formats cannot be found, GetStandardFormats returns a noTypeErr result code.
RESULT CODES
noErr 0 No error
noTypeErr –102 Edition container not found
editionMgrInitErr –450 Manager not initialized
Reading and Writing Non-Edition Files
The Edition Manager never opens or closes an edition container directly—it calls the current edition opener. See “Subscribing to Non-Edition Files” earlier in this chapter for additional information.
To override the standard opener function, you should create an opener function that contains the following parameters.
FUNCTION MyOpener (selector: EditionOpenerVerb;
VAR PB: EditionOpenerParamBlock) : OSErr;
When this function is called by the Edition Manager, the selector parameter is set to one of the edition opener verbs (eoOpen, eoClose, eoOpenNew, eoCloseNew, eoCanSubscribe). The PB parameter contains an edition opener parameter block record.
Use the GetEditionOpenerProc function to locate the current edition opener procedure and use the SetEditionOpenerProc function to provide your own edition opener procedure.
Use the CallEditionOpenerProc function to call an edition opener procedure pointer and use the CallFormatIOProc function to call a format IO procedure.
1GetEditionOpenerProc
Use the GetEditionOpenerProc function to locate the current edition opener procedure.
FUNCTION GetEditionOpenerProc
(VAR opener: EditionOpenerProcPtr) : OSErr;
opener The opener parameter returns the pointer to the current edition opener procedure.
1SetEditionOpenerProc
Use the SetEditionOpenerProc function to provide your own edition opener procedure.
FUNCTION SetEditionOpenerProc
(opener: EditionOpenerProcPtr) : OSErr;
opener The opener parameter is a pointer to the edition opener procedure that you are providing.
1CallEditionOpenerProc
Use the CallEditionOpenerProc function to call an edition opener procedure pointer.
FUNCTION CallEditionOpenerProc
(selector: EditionOpenerVerb;
VAR PB: EditionOpenerParamBlock;
routine: EditionOpenerProcPtr) : OSErr;
selector When this function is called by the Edition Manager, the selector parameter is set to one of the edition opener verbs (eoOpen, eoClose, eoOpenNew, eoCloseNew, eoCanSubscribe).
PB The PB parameter contains an edition opener parameter block record.
routine The routine parameter is a pointer to an edition opener procedure.
TYPE EditionOpenerParamBlock =
RECORD
info: EditionInfoRecord; {edition container to }
{ be subscribed to}
sectionH: SectionHandle; {publisher or }
{ subscriber }
{ requesting open}
document: FSSpecPtr; {document passed}
fdCreator: OSType; {Finder creator type}
ioRefNum: LongInt; {reference number}
ioProc: FormatIOProcPtr; {routine to read }
{ formats}
success: Boolean; {reading or writing }
{ was successful}
formatsMask: SignedByte; {formats required to }
{ subscribe}
END;
To override the standard reading and writing functions, you should create an IO function that contains the following parameters.
FUNCTION MyIO (selector: FormatIOVerb;
VAR PB: FormatIOParamBlock) : OSErr;
Set the selector parameter to one of the format I/O verbs (ioHasFormat, ioReadFormat, ioNewFormat, ioWriteFormat). The PB parameter contains a format I/O parameter block record.
1CallFormatIOProc
Use the CallFormatIOProc function to call a format IO procedure.
FUNCTION CallFormatIOProc (selector: FormatIOVerb;
VAR PB:FormatIOParamBlock;
routine: FormatIOProcPtr) : OSErr;
selector Set the selector parameter to one of the format I/O verbs (ioHasFormat, ioReadFormat, ioNewFormat, ioWriteFormat).
PB The PB parameter contains a format I/O parameter block record.
routine The routine parameter is a pointer to a format I/O procedure.
Locating a Publisher and Edition From a Subscriber
FUNCTION GetEditionInfo (sectionH: SectionHandle;
VAR editionInfo: EditionInfoRecord) : OSErr;
FUNCTION GoToPublisherSection (container: EditionContainerSpec) : OSErr;
Edition Container Formats
FUNCTION GetStandardFormats (container: EditionContainerSpec;
VAR previewFormat: FormatType;
preview, publisherAlias,
formats: Handle) : OSErr;
Reading and Writing Non-Edition files
FUNCTION GetEditionOpenerProc (VAR opener: EditionOpenerProcPtr) : OSErr;
FUNCTION SetEditionOpenerProc (opener: EditionOpenerProcPtr) : OSErr;
FUNCTION CallEditionOpenerProc
(selector: EditionOpenerVerb;
VAR PB: EditionOpenerParamBlock;
routine: EditionOpenerProcPtr) : OSErr;
FUNCTION CallFormatIOProc (selector: FormatIOVerb;
VAR PB: FormatIOParamBlock;
routine: FormatIOProcPtr) : OSErr;
Application-Defined Routines
FUNCTION MyExpDlgHook (itemOffset: Integer; itemHit: Integer;
theDialog: DialogPtr;
yourDataPtr: Ptr) : Integer;
FUNCTION MyExpModalFilter (theDialog: DialogPtr;
VAR theEvent: EventRecord;
itemOffset: Integer; VAR itemHit: Integer; yourDataPtr: Ptr) : Boolean;
FUNCTION MyOpener (selector: EditionOpenerVerb;
VAR PB: EditionOpenerParamBlock) : OSErr;
FUNCTION MyIO (selector: FormatIOVerb;
VAR PB: FormatIOParamBlock) : OSErr;
Result Codes
noErr 0 No error
abortErr –27 Publisher has written a new edition
eofErr –39 No additional data in the format
fnfErr –43 Edition container not found
flLckedErr –45 Publisher writing to an edition
fBsyErr –47 Section doing I/O
rfNumErr –51 Bad edition reference number
permErr –54 Not a subscriber
wrPermErr –61 Not a publisher
noTypeErr –102 Format not available
memFullErr –108 Could not load package
userCanceledErr –128 User chose Cancel from dialog box
editionMgrInitErr –450 Manager not initialized or could not load package
badSectionErr –451 Not a valid section type
notRegisteredSectionErr –452 Not registered
badSubPartErr –454 Bad edition container spec or invalid edition container
multiplePublisherWrn –460 Already is a publisher
containerNotFoundWrn –461 Alias was not resolved
notThePublisherWrn –463 Not the publisher
The Apple Event Manager
Introduction to Apple Events2-6
Apple Events and Apple Event Objects2-9
Components of Apple Events2-12
Data Structures Within Apple Events2-17
Descriptor Records2-17
Descriptor Lists2-22
Responding to Apple Events2-25
Requesting Services Through Apple Events2-33
Working With Object Specifier Records2-38
The Classification of Apple Event Objects2-45
Object Classes2-45
Properties and Elements2-48
Resolving Object Specifier Records2-53
About the Apple Event Manager2-57
Using the Apple Event Manager2-59
Accepting an Apple Event2-60
Installing Entries in the Apple Event Dispatch Tables2-63
Installing Entries in the Object Accessor Dispatch Tables2-66
Installing Object Accessor Functions That Find Apple Event Objects2-68
Installing Object Accessor Functions That Find Properties2-71
Handling the Required Apple Events2-72
Required Apple Events2-72
Handling the Open Application Event2-75
Handling the Open Documents Event2-76
Handling the Print Documents Event2-78
Handling the Quit Application Event2-80
Handling Apple Events Sent by the Edition Manager2-81
Handling the Create Publisher Event2-82
Getting Data Out of an Apple Event2-85
Getting Data Out of an Apple Event Parameter2-87
Getting Data Out of an Attribute2-89
Getting Data Out of a Descriptor List2-91
Writing Apple Event Handlers2-93
Replying to an Apple Event2-96
Disposing of Apple Event Data Structures2-98
Interacting With the User2-100
Setting the Client Application’s User Interaction Preferences2-100
Setting the Server Application’s User Interaction Preferences2-102
Requesting User Interaction2-103
Creating an Apple Event2-110
Adding Parameters to an Apple Event2-111
Specifying Optional Parameters for an Apple Event2-112
Specifying a Target Address2-116
Creating an Object Specifier Record2-118
Creating a Simple Object Specifier Record2-123
Specifying the Container Hierarchy2-126
Creating a Complex Object Specifier Record2-128
Sending an Apple Event2-143
Dealing With Timeouts2-149
Writing an Idle Function2-150
Writing a Reply Filter Function2-152
Writing and Installing Coercion Handlers2-153
Writing Object Accessor Functions2-157
Writing Object Accessor Functions That Find Apple Event Objects2-159
Writing Object Accessor Functions That Find Properties2-167
Defining Tokens2-169
Supporting Whose Descriptor Records2-170
Writing Object Callback Functions2-173
Writing an Object-Counting Function2-175
Writing an Object Comparison Function2-177
Writing Marking Callback Functions2-179
Reference to the Apple Event Manager2-182
Data Structures2-182
Apple Event Manager Routines2-183
Creating and Managing the Apple Event Dispatch Tables2-183
Initializing the Object Support Library2-188
Setting Object Accessor Functions and Object Callback Functions2-189
Getting, Calling, and Removing Object Accessor Functions2-192
Dispatching Apple Events2-196
Getting Data or Descriptor Records from Apple Event Parameters and Attributes2-197
Counting the Items in Descriptor Lists2-203
Getting Items From Descriptor Lists2-203
Getting Data and Keyword-Specified Descriptor Records From AE Records2-207
Resolving Object Specifier Records2-209
Requesting User Interaction2-211
Requesting More Time to Respond to Apple Events2-214
Suspending and Resuming Apple Event Handling2-215
Creating Apple Events2-218
Creating and Duplicating Descriptor Records2-219
Creating Descriptor Lists and AE Records2-221
Creating Object Specifier Records2-222
Adding Items to Descriptor Lists2-228
Adding Data and Descriptor Records to AE Records2-231
Adding Parameters and Attributes to Apple Events2-232
Sending Apple Events2-237
Getting the Sizes and Descriptor Types of Descriptor Records2-240
Deleting Descriptor Records2-243
Deallocating Memory for Descriptor Records2-244
Deallocating Memory for Tokens2-245
Coercing Descriptor Types2-246
Creating and Managing the Coercion Handler Dispatch Tables2-247
Creating and Managing the Special Handler Dispatch Tables2-251
Application-Defined Functions2-254
Object Accessor Functions2-255
Object Callback Functions2-256
Summary of the Apple Event Manager2-265
2The Apple Event Manager
This chapter describes Apple events, Apple event objects, and the data structures and routines that your application can use to construct, send, receive, and process Apple events.
As explained in the chapter “The Event Manager” in Inside Macintosh: Macintosh Toolbox, the Event Manager lets applications communicate with each other by sending high-level events. Using Event Manager routines, your application can create and process its own high-level events.
However, effective interapplication communication requires that applications agree on a standard set of conventions—a common vocabulary. To provide such a standard, Apple Computer, Inc., has defined a protocol called the Apple Event Interprocess Messaging Protocol (AEIMP). High-level events that conform to this protocol are called Apple events. You can ensure effective communication between your application and other Macintosh applications by using this protocol.
The vocabulary of publicly available Apple events is defined in the Apple Event Registry: Standard Suites, which defines the standard Apple events that developers and Apple have developed for use by all applications. The Apple Event Developers Association (AEDA) acts as a clearinghouse for information about Apple events and maintains the Apple Event Registry: Standard Suites.
The main requirement for effective communication between applications is some method of referring to menu commands, windows, data (such as words or shapes), and other items within any application or its documents. The Apple Event Registry: Standard Suites makes this possible by defining classes of Apple event objects, which are distinct items in an application or any of its documents that can be described in an Apple event. Apple event objects are often, but not always, items that a user can differentiate and manipulate within an application, such as words, paragraphs, shapes, windows, menu commands, or style formats.
Most of the standard Apple events in the Apple Event Registry: Standard Suites require your application to support specific Apple event object classes. Support for the standard Apple events, including Apple event objects, allows your application to exchange services and information with any other application that supports the same Apple events. In addition, support for the standard Apple events ensures that you can make your application scriptable—that is, capable of responding to scripts written in a scripting language such as AppleScript, the system-wide scripting language currently being developed by Apple.
The Apple Event Manager is available only in system software version 7.0 or later. To determine whether the Apple Event Manager is available, use the Gestalt function. In order to support Apple event objects, you must also link the current version of the Object Support Library to your application when you compile it.
The interapplication communications architecture of system software version 7.0 currently consists of three main components: the Event Manager, the Program-to-Program Communications (PPC) Toolbox, and the Apple Event Manager. See the chapter “Introduction to Collaborative Computing” in this book for an overview of the relationships among these components.
To use this chapter, you should also be familiar with the chapters “The Event Manager” in Inside Macintosh: Macintosh Toolbox and “The Process Manager” in Inside Macintosh: Operating System. To allow your application to send Apple events to applications on other computers, you may wish to use the PPCBrowser function, which is described in the chapter “Program-to-Program Communications Toolbox” in this book.
While the Apple events used by the Edition Manager are discussed in this chapter, you must refer to the chapter “The Edition Manager” in this book for a full discussion of how to implement the Edition Manager’s publish and subscribe features.
This chapter begins with an introduction that explains important concepts you need to understand before you begin to implement Apple events in your own application. Following the introduction, a section called “About the Apple Event Manager” summarizes the steps you neeed to take in order to support Apple events in your application.
The remainder of the chapter describes in detail how to use the Apple Event Manager to
n accept an Apple event
n install Apple event handlers and object accessor functions in the appropriate dispatch tables
n handle the required Apple events and the Apple events sent by the Edition Manager
n extract data from an Apple event
n write Apple event handlers and related functions
n interact with the user when necessary
n create an Apple event
n create an object specifier record
n send an Apple event
n write object accessor functions that can locate Apple event objects in your application
Introduction to Apple Events
An Apple event is a high-level event that conforms to the Apple Event Interprocess Messaging Protocol. The Apple Event Manager uses the services of the Event Manager to send Apple events between applications on the same computer or between applications on remote computers.
Applications typically use Apple events to request services and information from other applications or to provide services and information in response to such requests. For example, the Open Documents event requests that your application open specified documents. When your application supports this Apple event, it should respond by opening those documents in the manner that your application normally opens documents.
Communication between two applications that support Apple events is initiated by a client application, which sends an Apple event to request a service or information. For example, a client application might request services such as printing specific files, spell-checking a list of words, or performing a numerical calculation; or it might request information, such as one customer’s address or a list of names and addresses for all customers living in Ohio. The application providing the service or the requested information is called a server application. The client and server applications can reside on the same local computer or on remote computers connected to a network.
Figure 2-1 shows a common Apple event, the Open Documents event. The Finder application is the client; it requests that the SurfWriter application open the documents named Dec. Invoice and Nov. Invoice. The SurfWriter application responds to the Finder’s request by opening windows containing the specified documents.
An Open Documents event
The Finder is considered the client application for the Open Documents event shown in Figure 2-1 because the Finder initiates the request for a service. The Finder can also be considered the source application for the same Open Documents event. A source application for an Apple event is one that sends an Apple event to another application or to itself. Similarly, the SurfWriter application can be described as either the server application or the target application for the Open Documents event shown in Figure 2-1. A target application for an Apple event is the one addressed to receive the Apple event. The terms client application and source application are not always synonymous, nor are the terms server application and target application. Typically, an Apple event client application sends an Apple event requesting a service to an Apple event server application; in this case, the server application is the target application for the Apple event. A server application may send back a different Apple event as a response—in which case, the client application becomes the target application for the responding Apple event.
In order to perform the requested service—that is, to open the specified documents—the SurfWriter application shown in Figure 2-1 must be able to extract information from the Apple event that tells what kind of event it is (the Open Documents event) and which documents to open (Dec. Invoice and Nov. Invoice.) To identify Apple events and respond appropriately, every application can rely on a small vocabulary of standard Apple events that developers and Apple have established for all applications to use.
The standard Apple events are defined in the Apple Event Registry: Standard Suites. The standard suites, or groups of related Apple events that are usually implemented together, include the following:
n The Required suite consists of the four Apple events that the Finder sends to applications. These events are called Open Documents, Open Application, Print Documents, and Quit Application. The Finder uses the required events as part of the mechanisms in system software version 7.0 for launching and terminating applications. Your application must support the required Apple events as described in “Handling the Required Apple Events,” which begins on page 2-72, in order to be 7.0-friendly.
n The Core suite consists of the basic Apple events that nearly all applications use to communicate, including Get Data, Move, Delete Element, Save, and Undo. You should support all the Apple events in the Core suite that make sense for your application.
n Functional-area suites consist of groups of Apple events that support related functional areas, and include the Text Suite, the QuickDraw Graphics suite, and the Database suite. You can decide which functional area suites to support according to the features provided by your application. For example, most word-processing applications should support the Text suite, and most graphics applciations should support the QuickDraw Graphics suite.
If necessary, you can extend the definitions of the standard Apple events to match specific capabilities of your application. You can also define your own custom Apple events; however, before deciding whether you need to define custom Apple events, you should check with the Apple Event Developers Association (AEDA) to find out whether Apple events that already exist or are under development can be adapted to the needs your application.
Custom Apple events require other applications to support them explicitly. If all applications relied solely on custom Apple events for interapplication communication, each application would have to support all other applications’ custom Apple events. Instead of creating custom Apple events, it is usually preferable use the standard Apple events and extend their definitions as necessary for your application.
By supporting the standard Apple events in your application, you can ensure that your application can communicate effectively with other applications that also support them. Instead of supporting many different custom events for a limited number of applications, you can support a small number of standard Apple events that can be used by any number of applications. Supporting the standard Apple events also ensures that you can make your application scriptable, or capable of responding to instructions written in a scripting language such as AppleScript, the system-wide scripting language currently being developed by Apple.
The remainder of this introduction describes how applications can use Apple events and Apple event objects to request or provide services, what Apple events contain, the data structures from which they are constructed, and other important concepts you need to understand before you begin implementing the standard Apple events in your application. However, if you intend to start by providing support only for the Required suite of Apple events, you can skip the last three sections of this introduction (“Working With Object Specifier Records,” “The Classification of Apple Event Objects,” and “Resolving Object Specifier Records”) until you are ready to begin implementing the Core suite of Apple events.
For more information about the steps you need to take to support Apple events in your application, see “About the Apple Event Manager,” which begins on page 2-57.
The next section, “Apple Events and Apple Event Objects,” provides an overview of the way Apple events can describe menu commands, data, and other items within another application or its documents. You need to understand the concepts described in the next section before you decide which of the standard Apple event suites you want to begin implementing.
Apple Events and Apple Event Objects
Figure 2-1 on page 2-7 illustrates how a client application can send an Open Documents event to a server application in order to request that the server application open specific documents. The server application only needs to identify the Apple event and open the specified documents. However, effective communication between applications requires a method of referring to menu commands, windows, data (such as words or shapes), and other items within a target application or its documents. The Apple Event Manager allows any application to construct and interpret references to such items by means of a standard classification scheme for Apple event objects.
An Apple event object is a distinct item in a target application or any of its documents that can be described within an Apple event. Apple event objects can be anything that an application can locate on the basis of such a description, including items that a user can differentiate and manipulate within an application, such as words, paragraphs, shapes, windows, menu commands, or style formats. All the standard suites of Apple events except for the Required suite include definitions of the classes of Apple event objects upon which the Apple events in the suite can act. In order to support Apple events other than the Required suite and those sent by the Edition Manager, your application must also support the corresponding Apple event objects.
The definition for each Apple event object class in the Apple Event Registry: Standard Suites determines only how that kind of Apple event object should be described within an Apple event, not how it should be represented internally by an individual application. You do not have to write your application in an object-oriented programming language in order to support Apple event objects. Instead, you need to organize your application so that it will be able to interpret a request for a specific Apple event object correctly.
Figure 2-2 shows a common Apple event, the Get Data event from the Core suite. In this example, the BeachCharter application is the client application; it requests data contained in a specific table in a SurfWriter document. To make sure it receives the data it wants, the BeachCharter application must include a description of the data as part of the Get Data event it sends to SurfWriter. This description identifies the requested data as a particular kind of Apple event object called a table, which is named “Summary of Sales, 1991” and is located in a document named “Sales Report.”
The SurfWriter application responds to the request by locating the specified table and sending a reply Apple event to the BeachCharter application. The reply Apple event returns the requested data to the BeachCharter application in the form requested by the Get Data event. When it receives the reply Apple event, the BeachCharter application displays the data in its active window in the form of a pie chart. (A client application can display the data returned by a reply Apple event in any way that is appropriate.)
The BeachWriter application shown in Figure 2-2 must be able to construct a standard Get Data Apple event that includes a description of the requested table, and the SurfWriter application must be able to extract information from the Get Data event that tells what kind of event it is and which data to get. The Apple Event Manager includes routines that allow your application both to construct Apple events and to extract information from them. The rules for constructing and interpreting different kinds of Apple events are described in the Apple Event Registry: Standard Suites. Your application must follow these rules when it constructs or interprets any standard Apple event that it supports. After your application has extracted information from an Apple event, it should perform the action associated with that event, including locating any specified Apple event objects.
A Get Data event
Apple events often correspond to the actions performed by menu commands. For example, the Quit, Delete, Undo, and Close events all perform the same actions as their menu equivalents. By supporting Apple events and related Apple event objects that correspond to actions and distinct items available to a user from within your application, you can allow a scripting language such as AppleScript to intercede comfortably between your applicaton’s visual interface—its menus, dialog boxes, and other visual means of interacting with the user—and its internal organization. This means that a script can perform any action or series of actions within your application that a user might normally perform, without reference to low-level events such as mouse clicks and menu selections.
A script is a series of statements in a scripting language that send Apple events to one or more applications in order to execute a series of tasks. Scripts are especially useful for conditional or repetitive operations that require precise execution of a sequence of tasks, and for tasks that involve several machines across a network. For example, a script might generate the Apple events that correspond to the instructions “Open application, open Daily Stock Report document, choose Get Latest Quotes menu command, save document, print document, and quit application.” The ability to control your application with scripts is the major benefit that users will receive as a result of your support for Core suite and any functional-area suites that are appropriate for your application.
Components of Apple Events
An Apple event consists of attributes (which identify the Apple event and denote its task) and, often, parameters (which contain data to be used by the target application). Applications use the Apple Event Manager to create Apple events. Using arguments you pass to the AECreateAppleEvent function and to other Apple Event Manager routines, the Apple Event Manager constructs the data structures that make up the attributes and parameters of an Apple event. Applications must use the Apple Event Manager’s AESend function to transmit the Apple event. After receiving an Apple event, applications must use Apple Event Manager routines to extract the event’s attributes and parameters.
Attributes are a fundamental component of Apple events. Apple event attributes are records that identify the event class, event ID, target application, and other characteristic of an Apple event. Taken together, the attributes of an Apple event denote the task to be performed on any data specified in the Apple event’s parameters. You must use Apple Event Manager routines to add attributes to an Apple event. After the attributes are part of the Apple event, you must use Apple Event Manager routines to extract and examine them.
An Apple event parameter is a record containing data that the target application uses. Unlike Apple event attributes (which contain information that can be used by both the Apple Event Manager and the target application), Apple event parameters contain data used only by the target application. For example, an attribute like the event ID is used by the Apple Event Manager to call a handler from the server application’s Apple event dispatch table, and the server application must have a handler to process the event identified by that attribute. By comparison, the list of documents contained in a parameter to an Open Documents event is used only by the server application. As with attributes, you must use Apple Event Manager routines to add parameters to an Apple event, and after parameters are attached to an Apple event, you must use Apple Event Manager routines to extract and examine them.
As explained in the preceding section, “Apple Events and Apple Event Objects,” your application must make use of Apple Event Manager routines to construct Apple events and extract information from them according to the conventions described in the Apple Event Registry: Standard Suites.
Note that Apple event parameters are different from the parameters of Apple Event Manager functions. Apple event parameters are records private to the Apple Event Manager; function parameters are arguments you pass to the function or that the function returns to you. You typically specify the Apple event parameters (as well as the attributes) in parameters to Apple Event Manager functions. For example, the AEGetParamPtr function uses a buffer to return the data contained in an Apple event parameter. You specify which Apple event parameter in one of the parameters of the AEGetParamPtr function.
Apple events are identified by their event class and event ID attributes. The event class is the attribute that identifies a group of related Apple events. The event class appears in the message field of the event record for an Apple event. For example, the four required Apple events have the value 'aevt' in the message fields of their event records. The value 'aevt' can also be represented by the kCoreEventClass constant. Several event classes are shown here:
Event class Value Description
kCoreEventClass 'aevt' A required Apple event
kAECoreSuite 'core' A Core Apple event
kAEFinderEvents 'FNDR' An event that the Finder accepts
kSectionEventMsgClass \qsect' An event sent by the Edition Manager
The event ID is the attribute that identifies the particular Apple event within its event class. In conjunction with the event class, the event ID uniquely identifies the Apple event and communicates what action the Apple event should perform. (The event IDs appear in the where field of the event record for an Apple event. For more information about event records, see the chapter ‘The Event Manager” in Inside Macintosh: Macintosh Toolbox.) For example, the event ID of an Open Documents event has the value 'odoc' (which can also be represented by the kAEOpenDocuments constant). The kCoreEventClass constant in combination with the kAEOpenDocuments constant identifies the Open Documents event to the Apple Event Manager.
Here are the event IDs for the four required Apple events:
Event ID Value Description
kAEOpenApplication 'oapp' Perform tasks required when a user
opens your application without
opening or printing any documents
kAEOpenDocuments 'odoc' Open documents
kAEPrintDocuments 'pdoc' Print documents
kAEQuitApplication 'quit' Quit your application
In addition to the event class and event ID attributes, every Apple event must include an attribute that specifies the target application’s address. As described in the previous section, “Apple Events and Apple Event Objects,” the target application is the one addressed to receive the Apple event. Your application can send an Apple event to itself or to another application (on the same computer or on a remote computer connected to the network).
As with attributes, there are various types of Apple event parameters. A direct parameter usually contains the data to be acted upon by the server application. For example, the direct parameter of the Print Documents event contains a list of documents. A direct parameter is usually a required parameter—a parameter that is required in order to carry out the task denoted by the Apple event. The Apple Event Registry: Standard Suites specifies which parameters are normally required for the standard Apple events. Some Apple events also take additional parameters, which the server application uses in addition to the data specified in the direct parameter. For example, an Apple event for arithmetic operations may include additional parameters that specify operands in an equation. Additional parameters may be required or optional.
The Apple Event Registry: Standard Suites describes all parameters as either required or optional. An optional parameter is a supplemental Apple Event parameter that also can be used to specify data to the server application. Optional parameters need not be included in an Apple event; default values for optional parameters are part of the event definition. The server application that handles the event must supply default values if the optional parameters are omitted.
The source application is responsible for identifying which Apple event parameters the server should treat as optional. This means that, for a specific event, the source application can force the target application to treat parameters that are listed as optional parameters in the Apple Event Registry: Standard Suites as if they were required, and vice versa. For more information about optional parameters, see “Specifying Optional Parameters for an Apple Event” on page 2-112.<36pt\>\x12 <8bat\>u
The next section, “Data Structures Within Apple Events,” describes the data structures the Apple Event Manager uses for Apple event attributes and parameters. The rest of this section provides an overview of the role attributes and parameters play in the Open Documents and Get Data events illustrated by Figure 2-1 and Figure 2-2.
Figure 2-3 shows in greater detail the components of the Open Documents event that was introduced in Figure 2-1.
Major components of an Open Documents event
To process the information contained in the Open Documents event, the SurfWriter application uses the AEProcessAppleEvent function. The AEProcessAppleEvent function provides an easy way for your application to extract the event class and event ID of any Apple event from the corresponding attributes and call the code in your program that handles the Apple event.
The definition of a given Apple event in the Apple Event Registry: Standard Suites determines how the source application organizes the data in the Apple event’s parameters and how the target application interprets that data. The data in an Apple event parameter may be a string of text, a long integer, a Boolean value, an alias record, any of various other standard data types, or a description of an Apple event object. The code in your program that handles each Apple event you support interprets the data in an Apple event parameter differently depending on the kind of Apple event—that is, the event class and event ID.
Apple events can use standard data types, such as strings of text, long integers, and Boolean values, to contain the corresponding data in Apple event parameters. For example, the Get Data event can contain an optional parameter, specified as four-character string, that specifies the form in which the data requested by the client application should be returned. This optional parameter always consists of a four-character code. Apple events can also use special data types defined by the Apple Event Manager
Apple event parameters often contain descriptions of Apple event objects. An Apple event object is a distinct item in a target application or any of its documents that can be described precisely within an Apple event sent by a source application. These descriptions of Apple event objects make use of a standard classification scheme that provides a convenient method of referring to Apple event objects in other applications or their documents. The classification scheme used to describe Apple event objects is summarized in “The Classification of Apple Event Objects,” which begins on page 2-45. For information about the way specific kinds of Apple event objects fit into this scheme, see the Apple Event Registry: Standard Suites.
Apple event parameters can contain descriptions of one or more Apple event objects, but Apple event parameters never contain the Apple event objects themselves. Apple event objects can be anything that an application can locate on the basis of such a description, including items that a user can differentiate and manipulate, such as words, paragraphs, shapes, windows, menu commands, or style formats. For example, every Get Data event includes a required parameter that identifies the Apple event object whose data the client application is requesting, such as a word, a line, a paragraph, a related group of paragraphs, or the entire document. Thus one application can send a Get Data event to another application, requesting that the other application return one paragraph of a document, the first and last paragraphs of a document, all pictures in the document, all paragraphs containing the word “sales,” or pages 10 through 12 of the document.
Figure 2-4 shows in greater detail the components of the Get Data event that was introduced in Figure 2-2. The BeachCharter application sends a Get Data event to the SurfWriter application. The direct parameter for the Get Data event identifies the Apple event object requested as a table with the caption “Summary of Sales, 1991” in the document “Sales Report.” Both the table and the document are Apple event objects. The description of an Apple event object must include a description of where the Apple event object is located. The requested Apple event object is usually located within another Apple event object.
Major components of a Get Data event
To process the information contained in the Get Data event, the SurfWriter application calls the AEProcessAppleEvent function, which directs the Apple Event Manager to call the code in the SurfWriter application that handles the Get Data Apple event. The SurfWriter application responds to the Get Data event by resolving the description of the Apple event object—that is, by using the AEResolve function, other Apple Event Manager routines, and its own application-defined routines to locate the table named “Summary of Sales, 1991.” When the SurfWriter application locates the table, it sends a reply event containing the table’s data to the BeachCharter application. The BeachCharter application responds to the reply Apple event by displaying the data in its active window.
Data Structures Within Apple Events
An application must use Apple Event Manager functions to create, send, and process an Apple event. The Apple Event Manager constructs its own internal data structures to contain the information in an Apple event. To gain access to this data, the target application must almost always use Apple Event Manager functions. Neither the sender nor the receiver of an Apple event can directly manipulate data after it has been added to an Apple event record; each must rely on Apple Event Manager functions to do so. This section describes the data structures that the Apple Event Manager uses to create, send, and process Apple events.
The first data structure described in this section is the descriptor record, a data structure of type AEDesc that the Apple Event Manager uses for many different purposes. In some cases it is convenient to refer to descriptor records by data type names that indicate their contents; thus, the Apple Event Manager also defines data structures such as type AEAddressDesc, AEDescList, and AERecord, which are descriptor records used to hold addresses, lists of of other descriptor records, and Apple event parameters, respectively. These and most of the other data structures described in this section are formally defined as data structures of type AEDesc; they differ only in the purposes for which they are used.
Descriptor Records
Descriptor records are the fundamental structures from which Apple event attributes and parameters are constructed. A descriptor record is a data structure of type AEDesc; it consists of a handle to data and a descriptor type that identifies the type of the data referred to by the handle.
TYPE AEDesc =
RECORD {descriptor record}
descriptorType: DescType; {type of data being passed}
dataHandle: Handle {handle to data being passed}
END;
It is sometimes possible to retrieve the data associated with a handle in a descriptor record by dereferencing the handle twice. This will only work if the descriptor record is not part of an Apple event. After a descriptor record has been added to an Apple event, you must use Apple Event Manager routines to extract its data.
The descriptor type is a structure of type DescType, which in turn is of data type ResType—that is, a four-character string. Constants are usually used in place of these four-character strings when referring to descriptor types. Descriptor types represent various data types. Here is a list of the major descriptor type constants, their values, and the types of data they represent.
typeProcessSerialNumbe r 'psn ' Process serial number
typeNull 'null' NULL or nonexistent data
typeObjectSpecifier 'obj ' Object specifier record
typeObjectBeingExamined 'exmn' Part of object specifier record
typeCurrentContainer 'ccnt' Part of object specifier record
typeRelativeDescriptor 'rel ' Part of object specifier record
typeAbsoluteOrdinal 'abso' Part of object specifier record
typeIndexDescriptor 'inde' Part of object specifier record
Descriptor type Value Description
typeRangeDescriptor 'rang' Part of object specifier record
typeLogicalDescriptor 'logi' Part of object specifier record
typeCompDescriptor 'cmpd' Part of object specifier record
The constant typeObjectSpecifier and the constants that follow it in the preceding list designate special descriptor types used to define object specifier records, which are the data structures used for Apple event parameters that contain descriptions of Apple event objects. See “Working With Object Specifier Records” on page 2-38 for more information about object specifier records.
Figure 2-5 illustrates the logical arrangement of a descriptor record with a descriptor type of typeChar, which specifies that the data in the descriptor record is an unterminated string. The string in this descriptor record consists of the text “Summary of Sales, 1991.”
A descriptor record that contains an unterminated string.
Figure 2-6 illustrates the logical arrangement of a descriptor record with a descriptor type of typeType, which specifies that the data in the descriptor record must consist of a four-character code. The data in this descriptor record is specified by the constant kCoreEventClass, whose value is 'aevt'. As you will see by the end of this section, this descriptor record can be used in an Apple event attribute that identifies the event class ID for any Apple event in the Core suite.
A descriptor record that contains event class data
Every Apple event includes an attribute that contains the address of the target application. A descriptor record that contains an application’s address is called an address descriptor record.
TYPE AEAddressDesc = AEDesc; {address descriptor record}
As you will see later, the address in an address descriptor record can be specified as an application signature, a process serial number, a session reference number, a target ID record, or a data type that you define.
Like several of the other data structures defined by the Apple Event Manager for use in Apple event attributes and Apple event parameters, an address descriptor record is identical to a descriptor record of data type AEDesc; the only difference is that an address descriptor record must always contain an application’s address.
After the Apple Event Manager has assembled the necessary descriptor records as the attributes and parameters of an Apple event, your application cannot examine the contents of the Apple event directly. Instead, your appolication must use the Apple Event Manager routines to request each attribute and parameter by name. Applications identify attributes and parameters by means of keywords, which are arbitrary names used by the Apple Event Manager to keep track of various descriptor records. The AEKeyword data type is defined as a four-character code.
TYPE AEKeyword = PACKED ARRAY[1..4] OF Char;
{keyword for a descriptor }
{ record}
Constants are typically used for keywords. Here is a list of the keyword constants for Apple event attributes:
Attribute keyword Value Description
keyAddressAttr 'addr' Address of target application
keyEventClassAttr 'evcl' Event class of Apple event
keyEventIDAttr 'evid' Event ID of Apple event
keyEventSourceAttr 'esrc' Source of the Apple event
keyInteractLevelAttr 'inte' Settings for allowing the Apple Event
Manager to bring a server application
to the foreground
keyMissedKeywordAttr 'miss' First required parameter remaining in
an Apple event
keyOptionalKeywordAttr 'optk' List of optional parameters
for the Apple event
keyReturnIDAttr 'rtid' Return ID for reply Apple event
keyTimeoutAttr 'timo' Length of time in ticks that the client
will wait for a reply or a result from
the server
keyTransactionIDAttr 'tran' Transaction ID identifying a series of
Apple events
Here is a list of the keyword constants for commonly used Apple event parameters:
Parameter keyword Value Description
keyDirectObject '----' Direct parameter
keyErrorNumber 'errn' Error number parameter
keyErrorString 'errs' Error string parameter
keyProcessSerialNumber 'psn ' Process serial number parameter
The Apple Event Registry: Standard Suites defines additional keyword constants for Apple event parameters that can be used with specific Apple events.
The Apple Event Manager associates keywords with specific descriptor records by means of a keyword-specified descriptor record, which is a data structure of type AEKeyDesc that consists of a keyword and a descriptor record.
TYPE AEKeyDesc = {keyword-specified descriptor record}
RECORD
descKey: AEKeyword; {keyword}
descContent: AEDesc; {descriptor record}
END;
Figure 2-7 illustrates a keyword-specified descriptor record with the keyword keyEventClassAttr—the keyword that identifies an event class attribute. The figure shows the logical arrangement of the event class attribute for the Open Documents event shown in Figure 2-3 on page 2-14. The descriptor record in Figure 2-7 is identical to the descriptor record shown in Figure 2-6; its descriptor type is typeType, and its data identifies the event class as kCoreEventClass.
A keyword-specified descriptor record for the event class attribute of an Open Documents event
Descriptor Lists
When extracting data from an Apple event, you use Apple Event Manager functions to return data in a buffer specified by a pointer, or to return descriptor records containing the data, or to return lists of descriptor records (called descriptor lists) containing the data. As previously noted, the descriptor record (of data type AEDesc) is the fundamental structure in Apple events, and it contains a handle to data. A descriptor list is a data structure of type AEDescList defined by the data type AEDesc—that is, a descriptor list is a descriptor record that contains a list of other descriptor records.
TYPE AEDescList = AEDesc; {list of descriptor records}
Like several other Apple Event Manager data structures, a descriptor list is identical to a descriptor record of data type AEDesc; the only difference is that the data in a descriptor list must always consist of a list of other descriptor records.
Figure 2-8 illustrates the logical arrangement of the descriptor list contained by the direct parameter of the Open Documents event shown in Figure 2-3 on page 2-14. This descriptor list consists of a list of descriptor records that contain alias records to filenames. (“The Alias Manager” in Inside Macintosh: Operating System describes alias records in detail.)
A descriptor list for a list of aliases
Closely related to a descriptor list is a structure of data type AERecord; in fact, it is defined by the data type AEDescList.
TYPE AERecord = AEDescList; {list of keyword-specified }
{ descriptor records}
While a descriptor list is a descriptor record that contains a list of other descriptor records, an AE record of data type AERecord is a descriptor record that contains a list of keyword-specified descriptor records describing Apple event parameters. As with other Apple Event Manager data structures based on data type AEDesc, the main difference between a descriptor list and an AE record is the purpose for which each is used. Unlike a descriptor list, an AE record must always contain a list of keyword-specified descriptor records that describe Apple event parameters. It cannot contain keyword-specified descriptor records that describe Apple event attributes.
An Apple event record is a special descriptor list that consists of a structure of data type AppleEvent, which is defined as an AE record. An Apple event record is used to describe a full-fledged Apple event.
TYPE AppleEvent = AERecord; {list of attributes and }
{ parameters necessary for }
{ an Apple event}
An Apple event record is basically a descriptor record (of descriptor type typeAppleEvent) with a handle to a list of keyword-specified descriptor records. As with other Apple Event data structures based on data type AEDesc, the only difference between an Apple event record and an AE record is the purpose for which each is used. The data handles in an Apple event record’s keyword-specified descriptor records can refer either to attributes or to parameters, whereas the data handles in an AE record’s keyword-specified descriptor records can refer only to parameters. Similarly, an AE record can use only the keywords that identify Apple event parameters, whereas an Apple event record can use keywords that identify either attributes or parameters.
When you use the AECreateAppleEvent function, the Apple Event Manager creates an Apple event record containing the attributes for an Apple event’s event class, event ID, target address, return ID, and transaction ID. You then use Apple Event Manager functions such as AEPutParamDesc to add parameters to the Apple event.
Figure 2-9 shows an example of a complete Apple event—a data structure of type AppleEvent containing a list of keyword-specified descriptor records that name the attributes and parameters of an Open Documents event. The figure includes the event class attribute shown in Figure 2-7 and the descriptor list shown in Figure 2-8, which forms the direct parameter—the keyword-specified descriptor record with the keyword keyDirectObject. The entire figure corresponds to the Open Documents event shown in Figure 2-3 on page 2-14.
Because the internal structure of an Apple event record is identical to the structure of an AE record, you can pass an Apple event record to any Apple Event Manager function that expects an AE record. Since both are structures of data type AEDescList, which is derived from the data type AEDesc, you can also pass Apple event records and AE records, as well as descriptor lists and descriptor records, to any Apple Event Manager functions that expect records of data type AEDesc.
The next two sections, “Responding to Apple Events” and “Requesting Services Through Apple Events,” provide a quick overview of the steps your application must take to respond to and send Apple events.
Data structures within an Open Documents event
Responding to Apple Events
A client application uses the Apple Event Manager to create and send an Apple event requesting a service. A server application responds by using the Apple Event Manager to process the Apple event, to extract data from the attributes and parameters of the Apple event, and to return a result to the client application. The server provides its own routines for performing the action requested by the client’s Apple event.
As its first step in supporting Apple events, your application must be able to respond to the required Apple events sent by the Finder. If you plan to implement publish and subscribe capabilities, your application must respond to the Apple events sent by the Edition Manager. Your application should also be able to respond to the standard Apple events that other applications are likely to send to it or that it can send to itself. This section provides a q uick overview of the tasks your application must perform in responding to Apple events.
To respond to Apple events, your application must
n test for high-level events in its event loop
n use the AEProcessAppleEvent function to process Apple events
n provide handler routines for the Apple events it supports
n use Apple Event Manager functions to extract the parameters and attributes from Apple events
n use the AEInteractWithUser function—if your application requires input from the user when your application is responding to an Apple event—to bring your application to the foreground to interact with the user
n return a result for the client
Note that in order for your application to respond to Apple events sent from remote computers, the user of your application must allow network users to link to your application. To do this, the user selects your application in the Finder, chooses Sharing from the File menu, and then clicks the Allow Remote Program Linking check box. If the user has not yet started program linking, the Sharing command offers to display the Sharing Setup control panel so that the user can start program linking. The user must also authorize remote users for program linking by using the Users and Groups control panel. Program linking and setting up authenticated sessions are described in the chapter “Program-to-Program Communications Toolbox” in this book.
An Apple event (like all high-level events) is identified by a message class of kHighLevelEvent in the what field of the event record. You test the what field of the event record to determine whether an event is a high-level event. If the what field contains the value represented by the kHighLevelEvent constant and your application defines any high-level events other than Apple events, test the message field of the event record to determine whether the high-level event is something other than an Apple event. If the high-level event is not one that you’ve defined for your application, assume that it is an Apple event. (Note that you are encouraged to use Apple events instead of defining your own high-level events whenever possible.)
After determining that an event is an Apple event, use the AEProcessAppleEvent function to let the Apple Event Manager identify the event. Figure 2-10 shows how the SurfWriter application accepts and begins to process an Apple event sent by the Finder.
Accepting and processing an Open Documents event
The AEProcessAppleEvent function first identifies the Apple event by examining the data in the event class and event ID attributes. The AEProcessAppleEvent function then uses that data to call the Apple event handler that your application provides for that event. An Apple event handler is a function that extracts the pertinent data from the Apple event, performs the action requested by the Apple event, and returns a result. For example, if the event has an event class of kCoreEventClass and an event ID of kAEOpenDocuments, the AEProcessAppleEvent function calls your application’s routine for handling the Open Documents event.
You install Apple event handlers by using the AEInstallEventHandler function. This function creates an Apple event dispatch table that the Apple Event Manager uses to map Apple events to handlers in your application. After being called by the AEProcessAppleEvent function to process an Apple event, the Apple Event Manager reads the Apple event dispatch table and, if your application has installed a handler for that Apple event, calls your handler to finish responding to the event. Figure 2-11 shows how the flow of control passes from your application to the Apple Event Manager and back to your application.
The Apple Event Manager calling the handler for an Open Documents event
Your Apple event handlers must generally perform the following tasks:
n extract the parameters and attributes for the Apple event
n check that all the required parameters have been extracted
n locate any Apple event objects specified by object specifier records in the Apple event parameters
n set user interaction level preferences if necessary and, if your application needs to interact with the user, use the AEInteractWithUser function to bring it to the foreground
n perform the action requested by the Apple event
n dispose of any copies of descriptor records that have been created
n return a result for the client
You must use Apple Event Manager functions to extract the data from Apple events. You can also use Apple Event Manager functions to get data out of descriptor records, descriptor lists, and AE records. Most of these routines are available in two forms: one that uses a buffer to return a copy of the desired data, and one that returns a copy of the descriptor record containing the data. The following list shows the main functions you can use to access the data of an Apple event.
Function Description
AEGetParamPtr Uses a buffer to return the data contained in an Apple event parameter. Used to extract data of fixed length or known maximum length; for example, to extract the result code from the keyErrorNumber parameter of a reply Apple event.
AEGetParamDesc Returns the descriptor record or descriptor list for an Apple event parameter. Used to extract data of variable length; for example, to extract the descriptor list for a list of alias records specified in the direct parameter of the Open Documents event.
AEGetAttributePtr Uses a buffer to return the data contained in an Apple event attribute. Used to extract data of fixed length or known maximum length; for example, to determine the source of an Apple event by extracting the data from the keyEventSourceAttr attribute.
AEGetAttributeDesc Returns the descriptor record for an attribute. Used to extract data of variable length; for example, to make a copy of a descriptor record containing the address of an application.
AECountItems Returns the number of descriptor records in a descriptor list. Used, for example, to determine the number of alias records for documents specified in the direct parameter of the Open Documents event.
AEGetNthPtr Uses a buffer to return the data for a descriptor record that is contained in a descriptor list. Used to extract data of fixed length or known maximum length; for example, to extract a document’s alias record from the descriptor list specified in the direct parameter of the Open Documents event.
AEGetNthDesc Returns a descriptor record from a descriptor list. Used to extract data of variable length; for example, to get the descriptor record containing an alias record from the list specified in the direct parameter of the Open Documents event.
You can specify the descriptor type of the resulting data for these functions; if this is different from the descriptor type of the attribute or parameter, the Apple Event Manager attempts to coerce it to the specified type. In the direct parameter of the Open Documents event, for example, each descriptor record in the descriptor list is an alias record; each alias record specifies a document to be opened. As explained in the chapter “The File Manager” of Inside Macintosh: Operating System, all your application usually needs is the file system specification (FSSpec) record of the document. When you extract the descriptor from the descriptor list, you can request that the Apple Event Manager return the data to your application as a file system specification record instead of an alias record.
After extracting all known Apple event parameters, your handler should check that it retrieved all the parameters that the source application considered to be required parameters by determining whether the keyMissedKeywordAttr attribute exists. If the attribute exists, then your handler has not retrieved all the required parameters, and it should return an error.
The source application is responsible for identifying which Apple event parameters the server should treat as optional. This means that, for a specific event, the source application can force the target application to treat parameters that are listed as optional parameters in the Apple Event Registry: Standard Suites as if they were required, and vice versa. For more information about specifying which parameters the target application should treat as required and which it should treat as optional, see “Specifying Optional Parameters for an Apple Event” on page 2-112.<36pt\>\x12 <8bat\>u
If any of the Apple event parameters include object specifier records, your handler should use the AEResolve function, other Apple Event Manager routines, and your own application-defined routines to locate the corresponding Apple event objects. For more information about locating Apple event objects on the basis of information in object specifier records, see “Resolving Object Specifier Records” on page 2-53.
In some cases, the server may need to interact with the user when it handles an Apple event. For example, your handler for the Print Documents event may need to display a print options dialog box and get settings from the user before printing. Your handler should always use the AEInteractWithUser function before displaying a dialog box or alert box or otherwise interacting with the user. By specifying one of these flags to the AESetInteractionAllowed function, you can set your application’s user interaction level preferences.
Flag Description
kAEInteractWithSelf User interaction with your server application in response to an Alppe event may be allowed only when your application is also the client application—that is, only when your application is sending the Apple event to itself.
kAEInteractWithLocal User interaction with your server application in response to an Apple event may be allowed only if the client application is on the same computer as your application; this is the default if the server application does not call the AESetInteractionAllowed function.
kAEInteractWithAll User interaction with your server application inresponse to an Apple event may be allowed for any client application on any computer.
Both the client and server specify their preferences for user interaction: the client specifies whether the server should be allowed to interact with the user, and the server specifies when it will allow user interaction while processing an Apple event. For the Apple Event Manager to allow a server application to interact with the user in response to a client application’s Apple event, two conditions must be met. First, the client application must set flags in the sendMode parameter of the AESend function that indicate that it allows user interaction. Second, your server application must set the appropriate flag, as described in the preceding list, to allow user interaction in response to the Apple event sent from that client application. If these conditions are met and your application needs to interact with the user, the AEInteractWithUser function brings your application to the foreground if it isn’t already in the foreground. Your application can then display its dialog box or alert box or otherwise interact with the user. AEInteractWithUser brings your server application to the front either directly or after the user responds to a notification request.
When your application responds to an Apple event, it should perform the standard action requested by that event. For example, if the Apple event is the Open Documents event, your application should open the specified documents in titled windows just as if the user had selected each document from the Finder and then chosen Open from the File menu.
You should strive to create routines that can be called in response to both user events and Apple events. To do this, you need to isolate code for interacting with the user from the code that performs the requested action—such as opening a document. You then call the code that performs the requested action from your Apple event handler.<36pt\>\x12 <8bat\>s
When you extract a descriptor record by using the AEGetParamDesc, AEGetAttributeDesc, AEGetNthDesc, or AEGetKeyDesc function, the Apple Event Manager creates a copy of the descriptor record for you to use. When your handler is finished using a copy of a descriptor record, you should dispose of it—and thereby deallocate the memory it uses—by calling the AEDisposeDesc function.
Many Apple events can ask your application to return data. For example, if your application is a spelling checker, the client application probably expects data in the form of a list of misspelled words to be returned from your application. Similarly, the Get Data event shown in Figure 2-14 on page 2-44 requests that the server application locate a specific Apple event object and return the data associated with the Apple event object to the client application.
If the client application requests a reply, the Apple Event Manager prepares a reply Apple event for the client by passing a default reply Apple event to your handler. If the client application does not request a reply, the Apple Event Manager passes a null descriptor record (a descriptor record of type typeNull, which does not contain any data) to your handler instead of a default reply Apple event. The default reply Apple event has no parameters when it is passed to your handler. Your handler can add any parameters to the reply Apple event. If your application is a spelling checker, for example, you can return a list of misspelled words in a parameter. However, your handler should check the descriptor type of the reply Apple event before attempting to add any attributes or parameters to it. If your handler attempts to add an Apple event attribute or parameter to a null descriptor record, it will generate an error.
Your handler routine should always set its function result either to noErr if it successfully handles the Apple event or to a nonzero result code if an error occurs. If your handler returns a nonzero result code, the Apple Event Manager adds a keyErrorNumber parameter to the reply Apple event (unless you have already added a keyErrorNumber parameter). This parameter contains the result code that your handler returns. The client should check whether the keyErrorNumber parameter exists to determine whether your handler performed the requested action. In addition to returning a result code, your handler can also return an error string in the keyErrorString parameter of the reply Apple event. The client can use this string in an error message to the user.
If the client application requested a reply, the Apple Event Manager returns the reply Apple event to the client. The reply Apple event is identified by the event class kCoreEventClass and by the event ID kAEAnswer. When you have finished using the reply Apple event, you should dispose of it—and thereby deallocate the memory it uses—by calling the AEDisposeDesc function.
When your handler returns a result code to the Apple Event Manager, you have finished your response to the client application’s Apple event. Figure 2-12 shows the entire process of responding to an Apple event. The next section provides a quick overview of the steps your application must take to send Apple events.
Responding to an Open Documents event
Requesting Services Through Apple Events
Your application can use Apple events to request services from other applications. By using the core Apple event Get Data, for example, your application can request specific data from another application’s documents. By using functional-area Apple events, your application can request services from applications related to your own—for example, asking a spell-checking application to check the text in a document created by your application. Consult the Apple Event Registry: Standard Suites for the format and function of the standard Apple events that your application can send.
The previous section describes how a server application responds to a client application’s request for services. This section briefly describes the steps your application must take to act as a client application and request such services. To request a service through an Apple event, your application must
n create an Apple event by calling the AECreateAppleEvent function
n use Apple Event Manager functions to add parameters and any additional attributes to the Apple event
n call the AESend function to send the Apple event
n dispose of any copies of descriptor records that you have created
n process the reply Apple event (if necessary)
Use the AECreateAppleEvent function to create an Apple event record. Using the arguments you pass to the AECreateAppleEvent function, the Apple Event Manager constructs the data structures describing the event class, the event ID, and the target address attributes of an Apple event. The event class and event ID, of course, identify the particular event you wish to send. The target address identifies the application to which you wish to send the Apple event.
To act as a server for your application, the target application must support high-level events and must be open. The server can be your own application, another application running on the user’s computer, or an application running on another user’s computer connected to the network. Your application should offer some facility to launch a server application if it is not already running. It is recommended that you use the Open Selection event (identified by the event class kAEFinderEvents and the event ID kAEOpenSelection) to request that the Finder launch applications; however, the Process Manager also provides a means for your application to launch other applications. See the Apple Event Registry: Standard Suites for information on Finder events, and the chapter “Process Management” in Inside Macintosh: Operating System for information on using the Process Manager.
Your application should also allow the user to choose among the various applications available as servers. The PPCBrowser function allows users to select target applications on their own computers as well as those available on computers connected to the network. The PPCBrowser function presents a standard user interface for choosing a target application, much as the Standard File Package provides a standard user interface for opening and saving files. See the chapter “The Program-to-Program Communications Toolbox” in this book for details on using the PPCBrowser function.
If the server application is on a remote computer on a network, the user of that computer must allow program linking to the server application. The user of the server application does this by selecting the application in the Finder, choosing Sharing from the File menu, then clicking the Allow Remote Program Linking check box. If the user has not yet started program linking, the Sharing command offers to display the Sharing Setup control panel so that the user can start program linking. The user must also authorize remote users for program linking by using the Users and Groups control panel. Program linking and setting up authenticated sessions are described in the chapter “Program-to-Program Communications Toolbox” in this book.
You can specify two other attributes in the AECreateAppleEvent function: the reply ID and the transaction ID. For the reply ID attribute, you usually specify the kAutoGenerateReturnID constant to the AECreateAppleEvent function. This constant ensures that the Apple Event Manager generates a unique return ID for the reply Apple event returned from the server. For the transaction ID attribute, you’ll usually specify the kAnyTransactionID constant, which indicates that this Apple event is not one of a series of interdependent Apple events.
The Apple event record created with the AECreateAppleEvent function serves as a template for the Apple event you want to send. To add the remaining attributes and parameters necessary for your Apple event to the Apple event record, you must use these additional Apple Event Manager functions:
Function Description
AEPutParamPtr Takes a keyword, descriptor type, and pointer to data and adds the data to an Apple event record as a parameter with the specified keyword (replacing any existing parameter with the same keyword); used, for example, to put numbers into the parameters of an Apple event that asks the server to perform a calculation.
AEPutParamDesc Takes a keyword and a descriptor record and adds the descriptor record to an Apple event record as a parameter with the specified keyword (replacing any existing parameter with the same keyword); used, for example, to place a descriptor list containing alias records into the direct parameter of an Apple event that requests a server to manipulate files.
AEPutAttributePtr Takes a keyword, descriptor type, and pointer to data and adds the descriptor record to an Apple event record as an attribute with the specified keyword (replacing any existing attribute with the same keyword); used, for example, to change the event ID of an Apple event record that is waiting to be sent.
AEPutAttributeDesc Takes a keyword and a descriptor record and adds the descriptor record to an Apple event record as a attribute with the specified keyword (replacing any existing attribute with the same keyword); used, for example, to replace the descriptor record used for the target address attribute in an Apple event record waiting to be sent.
Descriptor records and descriptor lists are the basic components from which an Apple event record is constructed; these are passed to the AEPutParamDesc and AEPutAttributeDesc functions. Use the following functions to create descriptor records and descriptor lists:
Function Description
AECreateDesc Takes a descriptor type and a pointer to data and
converts them into a descriptor record.
AEPutPtr Takes a descriptor type and a pointer to data and adds
the data to a descriptor list as a descriptor record;
used, for example, to add to a descriptor list a
number that is used as the parameter of an Apple
event requesting a calculation.
AEPutDesc Adds a descriptor record to a descriptor list; used, for
example, to add to a descriptor list an alias record
that is used as the direct parameter of an Apple event
requesting file manipulation.
Apple event parameters for core events and functional-area events can include descriptions of Apple event objects in special records called object specifier records. For an overview of object specifier records and the routines you can use to create them, see “Working With Object Specifier Records,” which begins on page 2-38.
After you add all the attributes and parameters required for the Apple event, use the AESend function to send the Apple event. The Apple Event Manager uses the Event Manager to transmit the Apple event to the server application.
The AESend function requires that you specify whether and how your application should wait for a reply from the server. If you specify that you want a reply, the Apple Event Manager prepares a reply Apple event for your application by passing a default reply Apple event to the server. The Apple Event Manager returns any nonzero result code from the server’s handler in the keyErrorNumber parameter of the reply Apple event. The server can return an error string in the keyErrorString parameter of the reply Apple event. The server can also use the reply Apple event to return any data you requested—for example, the results of a numerical calculation or a list of misspelled words.
You specify how your application should wait for a reply by using one of these flags in the sendMode parameter of the AESend function:
Flag Description
kAENoReply Your application does not want a reply Apple event.
kAEQueueReply Your application wants a reply Apple event; the reply
appears in your event queue as soon as the server has
the opportunity to process and respond to your Apple
event.
kAEWaitReply Your application wants a reply Apple event and is
willing to give up the processor while waiting for the
reply; for example, if the server application is on the
same computer as your application, your application
yields the processor to allow the server to respond to
your Apple event.
If you specify the kAEWaitReply flag, you may provide an idle function. This function should process any events that occur while your application is waiting for a reply. You supply a pointer to your idle function as a parameter to the AESend function. So that your application can process other Apple events while it is waiting for a reply, you can also specify an optional filter function to the AESend function.
If you specify the kAENoReply flag, the reply Apple event prepared by the Apple Event Manager for the server application consists of a null descriptor record.
If your Apple event may require the user to interact with the server application (for example, to specify print or file options), you can communicate your user-interaction preferences to the server by specifying one of the following flags in the sendMode parameter of the AESend function:
Flag Description
kAENeverInteract The server application should never interact with the
user in response to this Apple event. If this flag is set,
AEInteractWithUser returns the
errAENoUserInteraction result code. This flag is
the default when an Apple event is sent to a remote
application.
kAECanInteract The server application can interact with the user in
response to this Apple event—by convention, if the
user needs to supply information to the server. If this
flag is set and the server allows interaction,
AEInteractWithUser either brings the server
application to the foreground or posts a notification
request. This flag is the default when an Apple event is
sent to a local application.
kAEAlwaysInteract The server application can interact with the user in
response to this Apple event—by convention,
whenever the server application normally asks a user
to confirm a decision or interact in any other way,
even if no additional information is needed from
the user. If this flag is set and the server allows
interaction, AEInteractWithUser either brings the
server application to the foreground or posts a
notification request.
kAECanSwitchLayer If both the client and server allow interaction, and if
the client application is the active application on the local machine and is waiting for a reply (that is, it has set the kAEWaitReply flag), AEInteractWithUser brings the server directly to the foreground. Otherwise, AEInteractWithUser uses the Notification Manager to request that the user bring the server application to the foreground.
The interpretation of the kAECanInteract and kAEAlwaysInteract flags depends on the server application only, and is not enforced by the Apple Event Manager; the server application must decide whether or not to call AEInterActWIthUser depending on which one is set.
The server application specifies its own preferences for user interaction while it is processing an Apple event by specifying flags to the AESetInteractionAllowed function, as described in the previous section. The interaction of the client and server applications’ preferences is explained in “Interacting With the User” on page 2-100.
After you send an Apple event, your application is responsible for disposing of the Apple event record—and thereby deallocating the memory it uses—by calling the AEDisposeDesc function. If you create one descriptor record and add it to another, the Apple Event Manager adds a copy of the newly created one to the existing one. For example, you might use the AECreateDesc function to create a descriptor record that you wish to add to an Apple event. When you use the AEPutParamDesc function, it adds a copy of your newly created descriptor record to an existing Apple event as a parameter.
Your application should dispose of all the descriptor records that are created in order to add parameters and attributes to an Apple event. You normally dispose of your Apple event and its reply after you receive a result from the AESend function. You should dispose of these even if AESend returns an error result. If your application requests a reply Apple event, your application must also dispose of the reply Apple event when it finishes processing the event.
Your application can request a reply Apple event. If you specify the kAEWaitReply flag, the reply Apple event is returned in a parameter you pass to the AESend function. If you specify the kAEQueueReply flag to the AESend function, the reply Apple event is returned in the event queue. In this case, the reply is identified by the event class kCoreEventClass and the event ID kAEAnswer; your application processes reply events that it receives in its event queue in the same manner that server applications process Apple events, as described earlier in “Responding to Apple Events.”
Your application should check for the keyErrorNumber parameter of the reply Apple event to ensure that the server performed the requested action. Any error messages that the server returns for you to display to your user will appear in the keyErrorString parameter.
When your handler is finished using a copy of a descriptor record used in the reply Apple event, you should dispose of them both—and thereby deallocate the memory they use—by calling the AEDisposeDesc function.
The next section provides an overview of the way a source application identifies Apple event objects within a target application or a target application’s documents. If you are starting by supporting only the Required suite and the Apple events sent by the Edition Manager, you can skip the next section and the remainder of this introduction and go directly to “About the Apple Event Manager,” which begins on page 2-57.
Working With Object Specifier Records
Most of the standard Apple events allow the source application to refer, in an Apple event parameter, to Apple event objects within the target application or its documents. The Apple Event Manager allows applications to construct and interpret such references by means of a standard classification system for Apple event objects. This system is fully described by the Apple Event Registry: Standard Suites, and is summarized in “The Classification of Apple Event Objects,” which begins on page 2-45. A description in an Apple event parameter that uses this classification system takes the form of an object specifier record.
This section describes object specifier records and the data structures used within them. You need to read this section if you plan to support the Core suite or any of the standard functional area suites, and if you want to make your application scriptable—that is, capable of responding to scripts written in a scripting language.
Object specifier records are descriptor records of descriptor type typeObjectSpecifier that are used by the Apple Event Manager to identify Apple event objects. Object specifier records can specify many combinations of characteristics that cannot be specified using one of the simple data types. For example, you can use object specifier records to specify cells in a table that include certain characters in a specific font, style, color, and point size. However, a client application’s ability to retrieve a specified Apple event object from a server application depends on the server application’s ability to locate the Apple event object. Thus, to locate characters of a specific color, your application must be able to identify a single character’s color; to locate any character in a cell, your application must be able to locate both the table and the cell.
An Apple event object described by an object specifier record exists only in the server application’s document or in the server application itself, not in the object specifier record. An object specifier record only identifies one or more Apple event objects among many; it contains a description of each Apple event object requested by the client application, not the Apple event object itself. <36pt\>\x12 <8bat\>s
Object specifier records are only valid while the Apple event that contains them is being handled. For example, if an application receives an Apple event asking it to cut row 5 of a table, what was row 6 then becomes row 5, and the original object specifier record that referred to row 5 no longer refers to the same row.
A source application can create object specifier records for use as Apple event parameters. Scripting languages can also create object specifier records as Apple event parameters for the Apple events they generate in the course of executing a script. A target application that receives an Apple event containing an object specifier record must resolve the object specifier record—that is, locate the requested Apple event object.
To support core and functional-area Apple events received by your application, you must define a hierarchy of Apple event objects within your application and its documents that you want other applications or scripting languages to be able to describe. The hierarchy of Apple event objects for your application should be based as closely as possible on the standard classficiation provided by the Apple Event Registry: Standard Suites. You do not need to write your application in an object-oriented programming language in order to support Apple event objects. Instead, you need to decide which of the standard Apple event objects make sense for your application and write functions that can locate them on the basis of information in an object specifier record. “Resolving Object Specifier Records,” which begins on page 2-53, provides an overview of the way the Apple Event Manager works with your application-defined functions to locate the Apple event objects described in an object specifier record.
If you want your application to send specific Apple events to other applications, you must also write functions that can create object specifier records and add them to Apple events. Your application does not need to create object specifier records in order to be scriptable—that is, capable of responding to scripts sent by a scripting language. However, you need to know how object specifier records are constructed in order to write functions that can help the Apple Event Manager resolve them.
An object specifier record has four components:
n an object class ID, which specifies the object class of the requested Apple event object
n a description of the container for the requested Apple event object; this usually identifies another Apple event object that contains the requested Apple event object
n a key form, which specifies how the Apple Event Manager should interpret the key data
n key data, which is used to distinguish the desired Apple event object from other Apple event objects of the same kind in the same container
For example, an object speciifer record that identifies a table named “Summary of Sales” in a document named “Sales Report” would specify the object class ID that identifies a table; a document named “Sales Report” as the container for the table; a key form constant indicating that the key data contains a name; and key data that consists of the string “Summary of Sales, 1991.”
The source application usually uses the CreatObjSpecifier function to specify the four components of an object specifier record. The server application uses the AEResolve function and other Apple Event Manager routines to extract information from an object specifier record and uses special routines of its own to locate the specified element on the basis of that information.
The CreateObjSpecifier routine creates an AE record, which it then coerces to a descriptor record with a descriptor type of typeObjectSpecifier. The typeObjectSpecifier descriptor type denotes an object specifier record: a descriptor record whose contents are defined by four descriptor records of type AEKeyDesc. The internal structure of an object specifier record is nearly identical to an AE record. They differ only in the content referred to by the data handles that they contain. An object specifier record is a structure of data type AEDesc containing four keyword-specified descriptor records that specify one or more Apple event objects; an AE record is a structure of data type AERecord containing one or more Apple event parameters.
The four keyword-specified descriptor records that constitute an object specifier record have these keywords:
Keyword Value Description
keyAEDesiredClass \qwant\q Object class ID
keyAEContainer \qfrom\q Identifies the container for this Apple
event object
keyAEKeyForm \qform\q The form taken by the key data
keyAEKeyData \qseld\q The key data
The object class ID specifies the Apple event object class to which the Apple event object belongs. An object class is a category for Apple event objects that share specific characteristics. The characteristics of each object class are listed in the Apple Event Registry: Standard Suites. For example, the Core suite defines object classes for documents, paragraphs, words, windows, and floating windows. The first keyword-specified descriptor record in an object specifier record, which has the keyword keyAEDesiredClass, specifies yhe object class ID with a four-character code. The object class ID can also be represented by a constant. Constants for object classes always begin with the letter c. The object class for words, for example, can be identified by either the object class ID \qcwor\q or the constant cWord.
The object class ID identifies the object class of an Apple event object described in an object specifier record, whereas the event class and event ID identify an Apple event. <36pt\>\x12 <8bat\>u
The container is usually another Apple event object that contains the Apple event object being specified. For example, the container for a document might be a window, and the container for characters, delimited items, or a word might be another word, a paragraph, or a document. The container is identified by the second keyword-specified descriptor record in an object specifier record, which has the keyword keyAEContainer. Since the container for an Apple event object is usually another Apple event object, this keyword-specified descriptor record usually consists of another object specifier record. It can also consist of a null descriptor record, or it can be used much like a variable when the Apple Event Manager determines a range or performs a series of tests.
The key form and key data distinguish the desired Apple event object from other Apple event objects of the same object class. The key form describes the form the key data takes. The third and fourth keyword-specified descriptor records in an object specifier record, which have the keywords keyAEKeyForm and keyAEKeyData, specify the key form and key data. Constants for key forms always begin with the word form. A key form of formAbsoluteposition and key data of 5 could be used to specify the fifth Apple event object in the container, such as the fifth row in a table. A key form of formName indicates key data that contains a name. A key form of formProperty indicates key data that specifies a property.
Properties are characteristics that can be used to describe Apple event objects belonging to the same class. The properties associated with the object class for documents include the name of the document and a flag that indicates whether the document has been modified since the last save. The properties associated with the object class for words include color, font, point size, and style.
Other key forms are used to specify relative positions, tests, and ranges. The key data for the key form formRelativePosition might specify that the requested Apple event object is located just after some other Apple event object. The key data for the key form formTest might instruct the server application to locate all the addresses in a database that share the zip code 94133. The key data for a key form of formRange might indicate that the key data specifies a range of Apple event objects.
The descriptor record that denotes the container for the object specifier record can in turn contain another object specifier record, and so on until the the Apple event object requested by the client application is fully specified. For example, an object specifier record that identifies a paragraph might specify the paragraph’s container with another object specifier record that identifies a page, which in turn might specify its container with another object specifier record that identifies a document. The ability to nest one object specifier record within another object specifier record in this way makes it possible to identify elements such as “the first row in the table named “Summary of Sales, 1991” in the document named “Sales Report.”
Figure 2-13 shows the structure of a simple object specifier record, which consists of four keyword-specified descriptor records that specify the class ID, the container, the key form, and the key data. These four keyword-specified descriptor records are the data for a descriptor record (AEDesc) of descriptor type typeObjectSpecifier. Note the similarities between the object specifier record shown in Figure 2-13 and the Apple event record shown in Figure 2-9 on page 2-24. Like an Apple event record or an AE record, an object specifier record consists of a list of keyword-specified descriptor records.
Data structures within a simple object specifier record
An object specifier record whose key form specifies that the key data should be interpreted as a property ID, a name, or an abolute position is called a simple object specifier record, and requires key data that consists of only one keyword-specified descriptor record, as shown in Figure 2-13. An object specifier record whose key form specifies that the key data should be interpreted as a test, a relative position, or a range is called a complex object specifier record, and requires key data that may consist of several interconnected keyword-specified descriptor records.
Figure 2-14 shows the object specifier record for the Get Data event previously illustrated in Figure 2-4 on page 2-16. The object class ID tells the SurfWriter application that the requested data is an element of class cTable. The container for the table is the document “Sales Report.” The key form is formName, which tells the server application that the key data identifies the Apple event object by name. The key data is the name of the table.
An object specifier record in a Get Data event
To add an object specifer record to an Apple event as one of its parameters, your application must first create the object specifier record. “Creating an Object Specifier Record,” which begins on page 2-118, describes the Apple Event Manager routines your application can use to create object specifier records.
In order to interpret object specifier records correctly, your application must make use of the standard classification system for Apple event objects. The next section summarizes the classification of Apple event objects as defined in the Apple Event Registry: Standard Suites.
The Classification of Apple Event Objects
To create and resolve object specifier records, your application should make use of the classification of Apple event objects defined by the Apple Event Registry: Standard Suites. This section summarizes the concepts that underlie that classification system. You should have a copy of the Apple Event Registry: Standard Suites available for reference purposes while you read this section.
You need the information in this section only if you plan to implement the core or functional-area Apple events. Before reading this section, you need to understand the concepts described in the preceding section, “Working With Object Specifier Records.”
You do not need to write your application in an object-oriented programming language in order to support Apple event objects in your application. You do need to understand the classification system described in this section in order to classify Apple event objects within your application and to write routines that can locate them on the basis of information contained in object specifier records.
Object Classes
Except for the concept of inheritance, Apple event objects are different from the objects used in object-oriented programming languages. Apple event objects are distinct items in a target application or any of its documents that can be specified by an object specifier record in an Apple event sent by a source application. Apple event objects are often, but not always, items that a user can differentiate and manipulate within an application, such as words, paragraphs, shapes, windows, menu commands, or style formats. Every Apple event object can be classified according to its object class, which defines both its characteristics and its behavior. The object classes listed in the Apple Event Registry: Standard Suites provide a method of describing Apple event objects that can be understood by all applications. Object classes permit more flexibility than simple descriptor types; for example, a word can be defined as a simple string, or it can be defined as an Apple event object with specific characteristics, such as font or style, attached to it.
The definition of an object class only specifies conventions that determine how applications should handle Apple event objects that belong to that class. Each application must make sure that it uses the conventions correctly; they are not enforced by the Apple Event Manager.<36pt\>\x12 <8bat\>u
Each object class is identified by a four-character object class ID, which can also be represented by a constant. Constants for object classes always begin with the letter c. For example, the object class for words can be identified by either the object class ID \qcwor\q or the constant cWord.
The definition of an object class specifies its superclass, which is the object class from which a subclass (the class being defined) inherits some of its characteristics. Characteristics can also be inherited from special object classes, called abstract superclasses, that are used only in definitions of object classes and do not refer to real Apple event objects. The pattern of inheritance among object classes is called the object class inheritance hierarchy. Figure 2-15 shows a portion of this hierarchy. The abstract superclass cAbstractObject is at the top of the hierarchy, and is therefore the only object class that has no superclass. cText, which is a regular object class, and cOpenableThing, which is an abstract superclass, are both subclasses of cAbstractObject and superclasses for their own subclasses. The object classes cWord, cItem, and cChar are all subclasses of cText, and cWindow, cDocument, and cFile are subclasses of cOpenableThing. Every object class inherits all the characteristics of its superclass, and can also add characteristics of its own.
Superclasses and subclasses
Here are some of the object classes defined for the Core suite:
Class Class ID Description
cChar 'cha ' Text characters
cClipboard 'clip' The Clipboard
cDocument 'docu' Macintosh documents
cFile 'cfil' Macintosh files
cItem 'citm' Delimited text strings
cSelection 'csel' User or application selections
cText 'ctxt' Series of characters
cWindow 'cwin' Standard Macintosh windows
cWord 'cwor' Words
Here are some of the object classes defined for the Text Suite:
Class Class ID Description
cChar 'cha ' Text characters
cLine 'clin' Lines of text
cParagraph 'cpar' Paragraphs
cText 'ctxt' Series of characters
cTextFlow 'cflo' Text flows
cWord 'cwor' Words
cWindow 'cwin' Standard Macintosh windows
As you can see, some object classes, such as cChar, cText, and cWord, are defined in more than one suite. For example, the definition of the cText object class in the Text suite is an extension of the cText object class defined in the core suite; it duplicates all the characteristics of the Core suite object class and adds some of its own. Like a word in a dictionary, the same object class IDs can have several related definitions. You can choose to support the definition that best suits your application; or, if necessary, you can create extensions of your own. Extensions to object classes are different than inheritance between object classes. An extension of a standard object class provides additional ways of describing an Apple event object of that class, whereas the object class inheritance hierarchy determines the pattern of characteristics shared by different object classes.
The definition of an object class always specifies a default descriptor type. When a client application requests some data from a server application, such as the data specified by a Get Data, Cut, or Copy event, and the client application does not specify a descriptor type for the returned data, the server application returns a descriptor record of the default descriptor type for the object class of the specified Apple event object. For example, the default descriptor type for Apple event objects of class cWord is typeText, a descriptor type that specifies an undelimited string of characters. The client application can also request that the data be returned in a descriptor record of some other data type.
The definition of an object class includes three lists of characteristics: properties, element classes, and Apple events that support the object class. (The next section describes properties and element classes.) Any or all of these characteristics may be inherited from a superclass. An Apple even is listed for an object class if its parameters can specify Apple event objects of that object class. The definition for cWindow, for example, lists fourteen Apple events whose parameters can include object specifier records that specify windows, including the Open, Close, and Move events. The cWindow class inherits all of these Apple events from its abstract superclass, cOpenableThing.
The Apple Event Registry: Standard Suites also defines primitive object classes, which are used to describe Apple event objects that contain a single value. For example, the cBoolean, cLongInteger, and cAlias object classes are all primitive object classes. The object class ID for a primitive object class is the same as the four-character value of its descriptor type. Primitive object classes contain no properties; they contain only the value of the data.
Properties and Elements
The properties listed for an object class are characteristics that can be used to describe Apple event objects that belong to that class. Each property is identified by a four-character property ID, which can also be represented by a constant. Constants for properties always begin with the letter p. Properties are themselves Apple e
Here are constants and property IDs for some properties:
Property Property ID Description
pName 'pnam' Name of an Apple event object
pBounds 'pbnd' The coordinates of a window
pVisible 'pvis' Indicates whether a window is visible
pIsModal 'pmod' Indicates whether a window is modal
pClass 'pcls' Class ID of an Apple event object
pFont 'font' Font
pTextStyle 'ptxs' Text style
pColor 'colr' Text color
pTextPointSize 'ptps' Point size
pScriptTag 'psct' Script system identifier
pFileInfo 'pfin' Information about a Macintosh file
pFillColor 'flcl' Fill color
The pName property for a document contains the document’s name. You can use the pName property to describe Apple event objects that have names.
The pVisible property for a window contains a Boolean value indicating whether or not a window is visible. You can use the pVisible property to check or set the visibility of a window.
A property is always defined by a single Apple event object. For example, the pFont property of a word is defined by the name of a font, such as New York; the string that identifies the font is an Apple event object of class cFont.
Instead of a specific object class, you can specify the constant cProperty as the object class for any object specifier record that identifies a property. An object specifier record for a property specifies the object class ID as cProperty, the Apple event object to which the property belongs as the container, formProperty as the key form, and a constant such as pFont as the key data. For example, if you were sending a Set Data event to change the font of a word to Palatino, the object specifier record for the property would specify cProperty for the class ID, an object specifier record for the word as the container, formProperty as the key form, and pFont as the key data. The Set Data Apple event parameter identified by the keyword keyAETheData would specify Palatino as the text to which to set the value of the specified property. The reply Apple event for a subsequent Get Data event that included an object specifier record for the same property would return the text Palatino in the parameter identified by the keyword keyDirectObject.
The elements of a specific Apple event object are the other Apple event objects, excluding those that define its properties, that it contains. An object specifier record for an element specifies the Apple event object in which the element is located as the container, and can specify any key form except for formProperty. Each object class definition in the Apple Event Registry: Standard Suites includes a list of element classes, which are the object classes of the elements that an Apple event object can contain. An Apple event object can contain only one of each of its properties, whereas it can contain many different elements of the same element class.
For example, since a paragraph can contain one or more words, one of the element classes listed for the object class cParagraph is the object class cWord. However, a paragraph can have only one pFont property, which is defined as the font of the first character in the paragraph and consists of the name of a font.
The properties and element classes listed for each object class definition in the Apple Event Registry: Standard Suites can be inherited from a superclass, or they can originate with a subclass. Figure 2-16 illustrates the object class inheritance hierarchy for the object class cWindow in the Core suite. Boldface terms in the figure represent those properties, element classes, or Apple events that are not inherited. The object class cWindow includes all the properties and Apple events of its superclass, cOpenableThing, which in turn includes all the properties and Apple events of its superclass, cAbstractObject. The object class cWindow also includes eight properties and one element class that originate with cWindow and are not inherited.
The object class inheritance hierarchy for the object class cWindow
The pClass property—the property that specifies the four-character class ID—originates with cAbstractObject. Since the definitions of all object classes are ultimately derived from cAbstractObject, pClass is inherited by all object classes. The definition for cAbstractObject also lists 12 Apple events, which include common events such as Get Data, Move, and Delete Element. Because cAbstractObject is at the top of the object class inheritance hierarchy, these twelve Apple events can use object specifier records that describe Apple event objects of any object class as a direct parameter. Like all abstract superclasses, cAbstractObject does not correspond to a real Apple event object, so its definition does not list any element classes. Unlike any other object class, cAbstractObject is at the top of the object class inheritance hierarchy, and therefore does not have a superclass.
The chain of containers that determine the location of one or more Apple event objects is called the container hierarchy. The container hierarchy, which specifies the location of real Apple event objects, is different from the object class inheritance hierarchy, which is an abstract concept that determines which properties, element classes, and Apple events an object class inherits from its superclass. For example, the container hierarchy for an Apple event object of class cWord can vary from one word to another, since a word can be contained in various combinations of other Apple event objects, such as a document, a paragraph, a delimited string, or another word.
Applications that support Apple event objects must be able to identify the order of several elements of the same class that are contained within another Apple event object. For example, each word in a paragraph should have an identifiable order, such as the fifth word or the twelfth word. This allows other applications to identify Apple event objects by describing their absolute position within a container.
Figure 2-17 shows an Apple event object of object class cWord—the word “Sales”—contained in another Apple event object of object class cParagraph. (Both these object classes are defined in the Text suite.) The figure shows only a portion of the container hierarchy for the word, since a complete description of the word would also include the containers that specify the location of the paragraph.
Your application must take account of the definitions in the Apple Event Registry: Standard Suites for any object classes you want to support. For example, the definition for the object class cText lists words, characters, and delimited items as Apple event objects that can be contained in Apple event objects of class cText. In order to support Apple events that refer to elements of object class cText, your application can associate the cText object class with words, characters, and delimited items in its documents. The definition for class cText also lists the properties font, style, color, point size, and script tag. If you want to support Apple events that distinguish a boldface 12-point word of object class cText from an italic 14-point word, for example, your application must associate the point size and style of text in its documents with the point size and style properties defined for class cText.
An Apple event object of class cWord contained in an Apple event object of class cParagraph
Resolving Object Specifier Records
If an Apple event parameter consists of an object specifier record, your handler for the Apple event should resolve the object specifier record: that is, locate the Apple event objects it describes. The first step is to call the AEResolve function with the object specifier record as a parameter. The AEResolve function performs tasks that are required to resolve any object specifier record, such as parsing its contents, keeping track of the results of tests, and handling memory management. When necessary, AEResolve calls application-defined functions to perform tasks that are unique to the application, such as locating a specific Apple event object in the application’s data structures or counting the number of Apple event objects in a container.
The section “Responding to Apple Events,” which begins on page 2-25, provides an overview of the steps your application must take in order to respond to Apple events. This section describes how you can use the Apple Event Manager and your own application-defined routines to resolve any object specifier records contained within Apple events to which you want your application to respond.
The AEResolve function can call two kinds of application-defined functions. Object accessor functions locate Apple event objects. Every application that supports simple object specifier records must provide one or more object accessor functions. This section provides an overview of the way AEResolve calls object accessor functions when it resolves object specified records. Object callback functions perform other tasks that only an application can perform, such as counting, comparing, or marking Apple event objects. You can provide up to seven object callback functions, depending on the needs of your application.
Each time AEResolve calls one of your application’s object accessor functions successfully, the object accessor function returns a special descriptor record created by your application, called a token, that identifies either a requested Apple event object in a specified container or a requested property of a specified Apple event object. AEResolve examines the token’s descriptor type, but does nothing with the token’s data; it simply passes the token back to your application when it needs to refer to the Apple event object or property the token identifies.
Each object accessor function provided by your application should either find elements of a specified object class contained in an Apple event object identified by a token of a specified descriptor type, or find properties of an Apple event object identified by a token of a specified descriptor type. The Apple Event Manager uses the object class ID of the specified Apple event object or property and the descriptor type of the token that identifies its container to determine which object accessor function to call.
It is up to you to decide how many object accessor functions you need to write for your application. You can write one object accessor function that locates Apple event objects of several different object classes; or you can write separate object accessor functions for certain object classes. Similarly, you may want to use only one descriptor type for all the tokens returned by your object accessor functions, or you may want to use several descriptor types. The way you define your tokens depends on the the needs of your application.
You install object accessor functions by using the AEInstallObjectAccessor function. Much like the AEInstallEventHandler function, AEInstallObjectAccessor creates an object accessor dispatch table that the Apple Event Manager uses to map requests for Apple event objects or properties of a specified object class in containers identified by a token of a specified descriptor type to the appropriate object accessor function in your application. Depending on the container hierarchy for a given object specifier record and the way your application defines its object accessor functions, the Apple Event Manager may need to call a series of object accessor functions in order to resolve the object specifier records nested in the keyword-specified descriptor record that describes an Apple event object’s container.
Figure 2-18 illustrates the major steps involved in resolving an object specifier record. The SurfWriter application shown in Figure 2-18 receives a Get Data event whose direct parameter is an object specifier record for a table named “Summary of Sales, 1991” in a document named “Sales Report.” The SurfWriter application’s handler for the Get Data event calls the AEResolve function with the object specifier record as a parameter. The AEResolve function begins to parse the object specifier record. The first object accessor function that AEResolve calls is always the function that can identify the Apple event object in the default container. (An application’s default container is the outermost container in the container hierarchy.) In Figure 2-18, the object specifier record for the document “Sales Report” specifies the default container, so the Apple Event Manager calls the object accessor function in the SurfWriter application that can locate a document in a containers identified by a token of descriptor type typeNull.
After the SurfWriter application has located the document named “Sales Report,” it returns a token to the Apple Event Manager—that is, a descriptor record that the SurfWriter application uses to identify the document. The Apple Event Manager examines the descriptor type of the token, but does not need to know anything about the token’s data in order to continue parsing the object specifier record. The next object accessor function it calls will be the function that can identify a table in a container identified by a token of descriptor type typeMyDocToken; when the Apple Event Manager calls this object accessor function, it passes the token describing the document to the function in order to specify the container for the requested table. After the SurfWriter application has located thetable named “Summary of Sales” in the document named “Sales Report,” it returns a token describing that table to the Apple Event Manager.
Resolving an object specifier record for a table in a document
Since the token returned to the Apple Event Manager at each stage provides all the information your application needs to locate the corresponding Apple event object, the Apple Event Manager needs to keep track of only one token at a time. Therefore, when your application returns a token to the Apple Event Manager, the previous token, if any, is no longer needed. The Apple Event Manager disposes of a token by calling either the AEDisposeDesc function or your application’s token disposal function, if you have provided one, which is an object callback function that disposes of a token. In Figure 2-18, the AEResolve function calls the SurfWriter application’s token disposal function after it recieves the token for the table in order to dispose of the token for the document. After the SurfWriter application has disposed of the token for the document, the AEResolve function returns the result of the resolution—that is, the token for the requested table—to the handler in the SurfWriter application that originally called AEResolve.
The Apple Event Manager can complete the cycle of parsing the object specifier record, calling the appropriate object accessor function to obtain a token, and disposing of the previous token as many times as it needs to in order to identify every container in the container hierarchy and finish resolving an object specifier record. However, one token will always be left over—the token that identifies the Apple event object requested by the Apple event (the innermost element in the container hierarchy). After your application receives this final token as the result of the AEResolve function and performs the action requested by the Apple event, it is up to your application to dispose of the token. Your application can do so by calling the AEDisposeToken function, which in turn calls either AEDisposeDesc or your application’s token disposal function.
You need to provide a token disposal function only if your application needs to do more than call AEDisposeDesc to dispose of a token, or if you provide marking callback functions, which are three object callback functions that allow your application to use its own marking scheme rather than tokens when identifying large groups of Apple event objects. Your application is not required to provide marking callback functions.
Applications that support complex object specifier records must provide at least two object callback functions: an object counting callback function, which counts the number of elements of a given object class in a given container so that the Apple Event Manager can determine how many elements it must test to find the element or elements that meet a specified condition; and an object comparison callback function, which compares one element to another element or to a descriptor record and returns TRUE or FALSE.
Your application may also provide an error callback function that can identify which descriptor record caused the resolution of an object specifier record to fail. Your application is not required to provide an error callback function.
If your application resolves object specifier records without the help of the Apple Event Manager, it must coerce the object specifier records into the equivalent descriptor records and then extract the necessary information from the descriptor records. The Apple Event Manager includes coercion handlers for these coercions.
For information about object accessor functions, see “Writing Object Accessor Functions,” beginning on page 2-157. For information about object callback functions, see “Writing Object Callback Functions,” beginning on page 2-173.
About the Apple Event Manager
You can use the Apple Event Manager to
n respond to the Apple events in the Required suite (Open Application, Open Documents, Print Documents, and Quit Application) that are sent by the Finder
n respond to the Apple events sent by the Edition Manager and allow users to share data among documents created by multiple applications
n respond to Apple events sent by other applications in order to request a service or information from your application
n send Apple events to other applications in order to request services or information from them
n respond to Apple events sent to your application by a script written in a scripting language such as AppleScript
The section “Introduction to Apple Events,” which begins on page 2-6, explains important concepts you need to know before you begin to implement Apple events in your own application. You do not need to implement all Apple events at once. If you want to begin by supporting only the required Apple events, you must
n set bits in the 'SIZE' resource to indicate that your application supports high-level events
n include code to handle high-level events in your main event loop
n install entries for the required Apple events in your application’s Apple event dispatch table
n write routines that handle the Required events
The following sections explain how to perform these tasks: “Accepting an Apple Event,” which begins on page 2-60, “Installing Entries in the Apple Event Dispatch Tables,” which begins on page 2-63, and “Handling the Required Apple Events,” which begins on page 2-72.
To support the Apple events sent by the Edition Manager in addition to the Required events, you must install entries for the Section Read, Section Write, Section Scroll, and Create Publisher events in your application’s Apple event dispatch table and write the corresponding handlers, as described in “Handling Apple Events Sent by the Edition Manager,” which begins on page 2-81.
It is relatively easy to support the required events and the events sent by the Edition Manager; however, if your application does not support any other Apple events, other applications will not be able to request services that involve locating specific Apple event objects within your application or its documents, and your application will not be able to respond to scripts. To provide full support for Apple events, your application must support both the Core suite of Apple events and any of the other functional-area standard suites that make sense for your application. For example, most word-processing applications would need to support the Text Suite, and most graphics applications would need to support the QuickDraw Graphics suite in addition to the Required suite and the Core suite.
By supporting all the suites in the Apple Event Registry: Standard Suites that are appropriate for your application, you ensure that your application can communicate effectively with all the other applications that support them. Instead of supporting many different custom events for a limited number of applications, you can support a small number of standard Apple events that can be used by any number of applications. Supporting the standard Apple events also ensures that you can make your application scriptable, or capable of responding to instructions written in a system-wide scripting language such as AppleScript.
To support any of the suites defined in the Apple Event Registry: Standard Suites besides the Required suite, you must also support the Apple event objects that can be described within Apple events that belong to the suites. Once you have provided the basic level of support for the Required suite and for events sent by the Edition Manager, you should
n decide which other Apple event suites you want to support
n define the hierarchy of Apple event objects within your application that you want other processes to be able to identify—that is, which Apple event objects can be contained by other Apple event objects in your application
n write routines that can handle the Apple events you support, and install corresponding entries in your application’s Apple event dispatch table
n write routines that can create the Apple events, including object specifier records if necessary, that you want your application to send to other applications
n write object accessor functions that can locate the Apple event objects you support, and install corresponding entries in your application’s object accessor dispatch table
n write any object callback functions that you decide to provide for optimizing the way your application locates requested Apple event objects
To decide which Apple event suites you want to support and how to define the hierarchy of Apple event objects in your application, consult the Apple Event Registry: Standard Suites and evaluate which Apple events and Apple event object classes make sense for your application. If necessary, you can extend the definitions of the standard Apple events and Apple events objects to cover special requirements of your application; it is preferable to extend the standard definitions rather than defining your own custom Apple events, since only those applications that choose to support your custom Apple events explicitly will be able to make use of them.
The next section, “Using the Apple Event Manager,” provides detailed information on writing and installing Apple event handlers and related functions, creating and sending Apple events, and writing and installing object accessor and object callback functions.
2The Apple Event Manager
Using the Apple Event Manager
The following sections explain in detail how to use the Apple Event Manager to accept, respond to, and send Apple events. The first three sections describe how to accept and process Apple events and how to install entries in the Apple event and object accessor dispatch tables. The fourth section fully explains how your application should handle the required Apple events, and it provides code that shows sample handlers for the required Apple events.
Additional sections describe how to
n handle events that support publish and subscribe features
n get data out of an Apple event
n write handlers that perform the action requested by an Apple event
n reply to an Apple event
n dispose of Apple event data structures
n interact with the user when processing an Apple event
n create an Apple event
n create an object specifier record
n send an Apple event
n write an idle function
n write a reply filter function
n write and install coercion handlers
n write object accessor functions
n write object callback functions
The Apple Event Manager (excluding the routines that support Apple event objects) is available only in system software version 7.0 and later versions. Use the Gestalt function with the gestaltAppleEventsAttr selector to determine whether the Apple Event Manager is available. In the response parameter, the bit defined by the constant gestaltAppleEventsPresent is set if the Apple Event Manager is available.
gestaltAppleEventsPresent = 0; {if this bit is set, }
{ then the Apple Event}
{ Manager is available}
To support the Apple events in the Core Suite and the functional area suites described in the Apple Event Registry: Standard Suites, your application must support Apple event objects. To make use of the Apple Event Manager routines that allow your application support Apple event objects, you must link the Object Support Library with your application when you build it, and call the AEObjectInit function before calling any of those routines.
Accepting an Apple Event
To accept or send Apple events (or any other high-level events), you must set the appropriate flags in your application’s 'SIZE' resource and include code to handle high-level events in your application’s main event loop.
Two flags in the 'SIZE' resource determine whether an application receives high-level events:
n The isHighLevelEventAware flag must be set for your application to receive any high-level events.
n The localAndRemoteHLEvents flag must be set for your application to receive high-level events sent from another computer on the network.
Note that in order for your application to respond to Apple events sent from remote computers, the user of your application must also allow network users to link to your application. The user does this by selecting your application in the Finder, choosing Sharing from the File menu, and clicking the Allow Remote Program Linking checkbox. If the user has not yet started program linking, the Sharing command offers to display the Sharing Setup control panel so that the user can start program linking. The user must also authorize remote users for program linking by using the Users and Groups control panel. Program linking and setting up authenticated sessions are described in the Program-to-Program Communications Toolbox chapter in this volume.
For a complete description of the 'SIZE' resource, see the chapter “The Event Manager” in Inside Macintosh: Macintosh Toolbox.
Apple events (and other high-level events) are identified by a message class of kHighLevelEvent in the what field of the event record. You can test the what field of the event record to determine whether the event is a high-level event.
Listing 2-1 is an example of a procedure called from an application’s main event loop that handles events, including high-level events. The procedure determines the type of event received and then calls another routine to take the appropriate action.
A DoEvent procedure
PROCEDURE DoEvent (event: EventRecord);
BEGIN
CASE event.what OF {determine the type of event}
mouseDown:
DoMouseDown (event);
.
. {handle other kinds of events}
.
{handle high-level events, including Apple events}
kHighLevelEvent:
DoHighLevelEvent (event);
END;
END;
Listing 2-2 is an example of a DoHighLevelEvent procedure that handles Apple events and also handles the high-level event identified by the event class mySpecialHLEventClass and the event ID mySpecialHLEventID. Note that, in most cases, you should use Apple events to communicate with other applications.
Listing 2-2 A DoHighLevelEvent procedure for handling Apple events and other high-level events
PROCEDURE DoHighLevelEvent (event: EventRecord);
VAR
myErr: OSErr;
BEGIN
IF (event.message = LongInt(mySpecialHLEventClass)) AND
(LongInt(event.where) = LongInt(mySpecialHLEventID)) THEN
BEGIN
{it's a high-level event that doesn't use AEIMP}
myErr := HandleMySpecialHLEvent(event);
IF myErr <> noErr THEN
DoError(myErr); {perform the necessary error handling}
END
ELSE {otherwise, assume that the event is an Apple event}
BEGIN
myErr := AEProcessAppleEvent(event);
IF myErr <> noErr THEN
DoError(myErr);
END;
END;
If your application accepts high-level events that do not follow the Apple Event Interprocess Messaging Protocol (AEIMP), you must dispatch these high-level events before calling AEProcessAppleEvent. To dispatch a high-level event that does not follow AEIMP, for each event you should check the event class, the event ID, or both to see if the event is one that your application can handle.
After receiving a high-level event (and, if appropriate, checking to see whether it is a type of high-level event other than an Apple event), your application typically calls the AEProcessAppleEvent function. The AEProcessAppleEvent function determines the type of Apple event received, gets the event buffer that contains the parameters and attributes of the Apple event, and calls the corresponding Apple event handler routine in your application.
You should provide a handler routine for each Apple event that your application supports. Your handler routine for a particular Apple event is responsible for performing the action requested by the Apple event, and your handler can optionally return data in the reply Apple event.
If the client application requests a reply, the Apple Event Manager passes a default reply Apple event to your handler. If the client application does not request a reply, the Apple Event Manager passes a null descriptor record (a descriptor record of type typeNull, which does not contain any data) to your handler instead of a default reply Apple event.
After your handler finishes processing the Apple event and adds any parameters to the reply Apple event, it should return a result code to AEProcessAppleEvent. If the client application is waiting for a reply, the Apple Event Manager returns the reply Apple event to the client.
Installing Entries in the Apple Event Dispatch Tables
When your application receives an Apple event, use the AEProcessAppleEvent function to retrieve the data buffer of the event and to route the Apple event to the appropriate Apple event handler in your application. Your application supplies an Apple event dispatch table to map the Apple events your application supports to the Apple event handlers provided by your application.
To create your application’s Apple event dispatch table (if it does not already exist) or install additional entries in it, use the AEInstallEventHandler function. You usually install entries for all of the Apple events that your application accepts into your application’s Apple event dispatch table.
For each Apple event your application supports, your Apple event dispatch table should include entries that specify
n the event class of the Apple event
n the event ID of the Apple event
n the address of the Apple event handler for the Apple event
n a reference constant
You provide this information to the AEInstallEventHandler function. In addition, you indicate to the AEInstallEventHandler function whether the entry should be added to your application’s Apple event dispatch table or the system Apple event dispatch table.
The system Apple event dispatch table is a table in the system heap that contains system Apple event handlers—handlers that are available to all applications and processes running on the same computer. The handlers in your application’s Apple event dispatch table are available only to your application. If AEProcessAppleEvent cannot find a handler for the Apple event in your application’s Apple event dispatch table, it looks in the system Apple event dispatch table for a handler. If it doesn’t find a handler there either, it returns the errAEEventNotHandled result code.
Listing 2-3 illustrates how to add entries for the required Apple events to your application’s Apple event dispatch table.
Listing 2-3 Adding entries for the required Apple events to an application’s Apple event dispatch table
The code in Listing 2-3 creates entries for all four required Apple events in the Apple event dispatch table. (For examples of handlers that correspond to these entries, see “Handling the Required Apple Events,” which begins on page 2-72.) The first entry creates an entry for the Open Application event. The entry indicates the event class and event ID of the Open Application event, supplies the address of the handler for that event, and specifies 0 as the reference constant.
The reference constant is passed to your handler by the Apple Event Manager each time your handler is called. Your application can use this reference constant for any purpose. If your application doesn’t use the reference constant, use 0 as the value.
The last parameter to the AEInstallEventHandler function is a Boolean value that determines whether the entry is added to the system Apple event dispatch table or to your application’s Apple event dispatch table. To add the entry to your application’s Apple event dispatch table, use FALSE as the value of this parameter. If you specify TRUE, the entry is added to the system’s Apple event dispatch table. The code shown in Listing 2-3 adds entries to the application’s Apple event dispatch table.
If your application supports the Edition Manager, you should also add entries to your application’s Apple event dispatch table for the Apple events that your application receives from the Edition Manager. Listing 2-4 shows how to add these entries.
Listing 2-4 Adding entries for Apple events sent by the Edition Manager to an application’s Apple event dispatch table
See “Handling Apple Events Sent by the Edition Manager” on page 2-81 for the parameters associated with these events. See the chapter “The Edition Manager” in this book for information on how your application should respond to the Apple events sent by the Edition Manager.
If you add a handler to the system Apple event dispatch table, the handler that you specify must reside in the system heap. If there was already an entry in the system Apple event dispatch table for the same event class and event ID, it is replaced unless you should chain it to your system handler as explained in “Creating and Managing the Apple Event Dispatch Tables” on page 2-183.
When an application calls a system Apple event handler, the A5 register is set up for the calling application. For this reason, if you provide a system Apple event handler, it should never use A5 global variables or anything that depends on a particular context; otherwise, the application that calls the system handler may crash.<36pt\>\x12 <8bat\>u
When the AEProcessAppleEvent function begins to process an Apple event, it first searches the application’s Apple event dispatch table, then the system Apple event dispatch table for the entry that corresponds to the Apple event’s event class and event ID. If the AEProcessAppleEvent function cannot find an entry for an Apple event’s handler in either table, it returns the result code errAEEventNotHandled to the Apple event server. If the client is waiting for a reply, AESend also returns this result code as its function result.
For any entry in your Apple event dispatch table, you can specify a wildcard value for the event class, event ID, or both. You specify a wildcard by supplying the typeWildCard constant when installing an entry into the Apple event dispatch table. A wildcard value matches all possible values. Wildcards make it possible to supply one Apple event handler that dispatches several related Apple events.
For example, if you specify an entry with the typeWildCard event class and the kAEOpenDocuments event ID, the Apple Event Manager dispatches Apple events of any event class with an event ID of kAEOpenDocuments to the handler for that entry.
If you specify an entry with the kCoreEventClass event class and the typeWildCard event ID, the Apple Event Manager dispatches Apple events of the kCoreEventClass event class with any event ID to the handler for that entry.
If you specify an entry with the typeWildCard event class and the typeWildCard event ID, the Apple Event Manager dispatches all Apple events of any event class and any event ID to the handler for that entry.
If an Apple dispatch table contains one entry for an event class and a specific event ID, and also contains another entry that is identical except that it specifies a wildcard value for either the event class or the event ID, the Apple Event Manager will dispatch the more specific entry. For example, if an Apple event dispatch table includes one entry that specifies the event class as kAECoreSuite and the event ID as kAEDelete, and another entry that specifies the event class as kAECoreSuite and the event ID as typeWildCard, the Apple Event Manager will dispatch the Apple event handler associated with the entry that specifies the event ID as kAEDelete.
If your application sends Apple events to itself using a typeProcessSerialNumber address descriptor record with the value kCurrentProcess, the Apple Event Manager jumps directly to the appropriate Apple event handler without going through the normal event-processing sequence. As a result, your application will not run appreciably more slowly when it sends Apple events to itself. Because the Apple Event Manager calls your application’s Apple event handlers directly, without going through the PPC Toolbox, Apple events your application sends to itself do not appear in your application’s high-level event queue.<36pt\>\x12 <8bat\>s
Installing Entries in the Object Accessor Dispatch Tables
Most of the Apple events in the Core suite and the functional-area suites defined in the Apple Event Registry: Standard Suites can include parameters that consist of object specifier records. If the direct parameter for an Apple event consists of an object specifier record, your handler for the event should call the AEResolve function to resolve the object specifier record: that is, to find the Apple event objects it describes and, if necessary, their properties. AEResolve resolves the object specifier record with the help of object accessor functions provided by your application. Your application supplies an object accessor dispatch table that the Apple Event Manager uses to map requests for Apple event objects or their properties to the appropriate object accessor functions. (For an overview of the way AEResolve works with your application’s object accessor functions to locate Apple event objects, see “Resolving Object Specifier Records,” which begins on page 2-53.)
Each time AEResolve calls one of your application’s object accessor functions, your object accessor function should return a token that identifies the specified Apple event object or a specified property of an Apple event object. Your object accessor function also returns a result code that indicates whether or not it found the Apple event object or property. The token, which is a descriptor record of data type AEDesc, can be of any descriptor type, including descriptor types you define yourself.
Each object accessor function provided by your application should either find elements of a specified object class contained in an Apple event object identified by a token of a specified descriptor type, or find properties of an Apple event object identified by a token of a specified descriptor type. The Apple Event Manager uses the object class ID of the specified Apple event object and the descriptor type of the token that identifies its container to determine which object accessor function to dispatch. For object accessor functions that find properties, you should specify the object class ID as the constant cProperty.
To create your application’s object accessor dispatch table (if it does not already exist) or install additional entries in it, use the AEInstallObjectAccessor function. For each object class and property your application supports, you should install entries that specify
n the object class of the requested Apple event object or property
n the descriptor type of the token used to identify the container for the requested Apple event object or property
n the address of the object accessor function that finds Apple event objects or properties of the specified object class in containers described by tokens of the specified descriptor type
n a reference constant
You provide this information in the first four parameters to the AEInstallObjectAccessor function. The fifth parameter allows you to indicate whether the entry should be added to your application’s object accessor dispatch table or the system object accessor dispatch table.
The system object accessor dispatch table is a table in the system heap that contains object accessor functions that are available to all processes running on the same computer. The object accessor functions in your application’s object accessor dispatch table are available only to your application. If AEResolve cannot find an object accessor function for the Apple event object class in your application’s object accessor dispatch table, it looks in the system object accessor dispatch table for an object accessor function. If it doesn’t find an object accessor function there either, it returns the result code errAEEventNotHandled.
If the AEResolve function successfully calls the appropriate object accessor function in either the application object accessor dispatch table or the system object accessor dispatch table, the object accessor function returns a token and result code, which AEResolve uses either to continue resolving the object specifier record or, if the token identifies the final Apple event object or property in the container hierarchy, to return as its function result.
It is up to you to decide how many object accessor functions you need to write and install for your application. You can install one object accessor function that locates Apple event objects of several different object classes, or you can write separate object accessor functions for certain object classes. Similarly, you may want to use only one descriptor type for all the tokens returned by your object accessor functions, or you may want to use several descriptor types. The sections that follow provide examples of alternative approaches.
For more information about object accessor functions, see “Writing Object Accessor Functions,” which begins on page 2-157.
Installing Object Accessor Functions That Find Apple Event Objects
Listing 2-5 demonstrates how to add entries to your application’s object accessor dispatch table for the object class cText and three of its element classes: the object classes cWord, cItem, and cChar. In this example, the container for each of these object classes is identified by a token that consists of a descriptor record of descriptor type typeMyText.
Listing 2-5 Adding entries to an application’s object accessor dispatch table for object accessor functions that locate elements of different object classes in containers identified by tokens of the same descriptor type
The first call to AEInstallObjectAccessor in Listing 2-5 adds an entry to the application’s object accessor dispatch table indicating that the AEResolve function should call the MyFindTextObjectAccessor function when resolving any Apple event object with the cText object class and a container identified by a token of descriptor type typeMyText. The other calls to AEInstallObjectAccessor in Listing 2-5 add entries for Apple event objects of object classes cWord, cItem, and cChar in a container identified by a token of descriptor type typeMyText. For example, since all the entries created by the code in Listing 2-5 specify the descriptor type typeMyText for the token that identifies the container, the AEResolve function will call the MyFindWordObjectAccessor function to locate a requested word regardless of whether the container for the word is a run of text, another word, a paragraph, or an item.
The fourth parameter for the AEInstallObjectAccessor function specifies a reference constant that is passed to your handler by the Apple Event Manager each time AEResolve calls your object accessor function. Your application can use this reference constant for any purpose. If your application doesn’t use the reference constant, use 0 as the value, as shown in Listing 2-5.
The last parameter for the AEInstallObjectAccessor function is a Boolean value that determines whether the entry is added to the system object accessor dispatch table or to your application’s object accessor dispatch table. To add the entry to your application’s object accessor dispatch table, use FALSE as the value of this parameter. If you specify TRUE, the entry is added to the system’s object accessor dispatch table.
If you add an object accessor function to the system object accerssordispatch table, the function that you specify must reside in the system heap. If there was already an entry in the system object accessor dispatch table for the same object class and container descriptor type, it is replaced.
When an application calls a system object accessor function, the A5 register is set up for the calling application. For this reason, if you provide a system object accessor function, it should never use A5 global variables or anything that depends on a particular context; otherwise, the application that calls the system object accessor function may crash.<36pt\>\x12 <8bat\>u
The code shown in Listing 2-5 installs a separate object accessor function for each object class, even though it specifies the same descriptor type for tokens that identify the containers for Apple event objects of each class. Most word-processing applications can specify the same object accessor function as well as the same token descriptor type for Apple event objects of these four classes, in which case the code shown in Listing 2-5 can be altered as shown in Listing 2-6.
Listing 2-6 Adding entries to an application’s object accessor dispatch table for one object accessor function that locates elements of different object classes in containers identified by tokens of the same descriptor type
In some situations you may want to write different object accessor functions to locate Apple event objects of the same object class that can be located in containers identified by tokens of different descriptor types. For example, the code in Listing 2-7 installs two different object accessor functions: one that finds a word in a container identified by a token of type typeMyTextToken, and one that finds a word in a container identified by a token of typeMyGraphicTextToken.
Listing 2-7 Adding entries to an application’s object accessor dispatch table for object accessor functions that locate elements of the same object class in containers identified by tokens of different descriptor types
Every application must provide one or more object accessor functions that can find Apple event objects in the default container, which is always identified by a token of descriptor type typeNull. Listing 2-8 demonstrates how to add entries to your application’s object accessor dispatch table for the object classes cDocument and cWindow. The container for each of these classes is identified by a token of descriptor type typeNull, which specifies an application’s default container.
Listing 2-8 Adding entries to an application’s object accessor dispatch table for object accessor functions that locate Apple event objects of different object classes in the default container
For any entry in your object accessor dispatch table, you can specify a wildcard value for the object class, a wildcard value for the descriptor type of the token used to identify the container, or both. You specify a wildcard by supplying the typeWildCard constant when installing an entry into the object accessor dispatch table. A wildcard value matches all possible values.
For example, if you specify typeWildCard as the first parameter and typeMyToken as the second parameter for the AEInstallObjectAccessor function, the Apple Event Manager calls the object accessor function that you specify in the third parameter when resolving Apple event objects of any object class in containers identified by tokens of the typeMyToken descriptor type.
If you specify cText as the first parameter and typeWildCard as the second parameter for the AEInstallObjectAccessor function, the Apple Event Manager calls the object accessor function that you specify in the third parameter when resolving Apple event objects of the object class cText in containers identified by tokens of any descriptor type.
If you specify typeWildCard as the first parameter and typeWildCard as the second parameter for the AEInstallObjectAccessor function, the Apple Event Manager calls the object accessor function that you specify in the third parameter when resolving Apple event objects of any object class in containers identified by tokens of any descriptor type.
If an object accessor dispatch table contains one entry for a specific object class and a specific token descriptor type, and another entry that is identical except that it specifies a wildcard value for either the object class or the token descriptor type, the Apple Event Manager will dispatch the more specific entry. For example, if an object accessor dispatch table includes one entry that specifies the object class as cWord and the token descriptor type as typeMyTextToken, and another entry that specifies the object class as cWord and the token descriptor type as typeWildCard, the Apple Event Manager will dispatch the object accessor function associated with the entry that specifies typeMyTextToken.
Installing Object Accessor Functions That Find Properties
The Apple event object to which a property belongs is that property’s container. You should add entries to your application’s object accessor dispatch table that specify object accessor functions for finding properties in containers identified by tokens of various descriptor types. Object specifier records do not specify a property’s specific object class; instead, they specify the constant cProperty as the class ID for any property. Similarly, you should specify the constant cProperty as the object class for an object accessor function that can find any property of a container identified by a token of a given descriptor type. If you need to install different object accessor routines for finding properties of Apple event objects that belong to different object classes, you must use different descriptor types for the tokens that represent those Apple event objects.
For example, to specify an object accessor function that locates properties of Apple event objects identified by tokens of descriptor type typeMyToken, you can add a single entry to the object accessor dispatch table:
The code in this example adds an object accessor function to the application’s object accessor dispatch table that can find any property of any container identified by a token of descriptor type typeMyToken. If the second parameter were specified as typeWildCard, the MyFindPropertyObjectAccessor function would have to be capable of finding any property of any Apple event object in your application.
Handling the Required Apple Events
This section describes the required Apple events—the Apple events your application must support to be 7.0-friendly—and the descriptor types for all parameters of the required Apple events. It also describes how to write the handlers for these events, and it provides sample code.
To support the required Apple events, you must set the necessary flags in the 'SIZE' resource of your application, install entries in your application’s Apple event dispatch table, add code to the event loop of your application to recognize high-level events, and call the AEProcessAppleEvent function, as described in “Accepting an Apple Event,” which begins on page 2-60, and “Installing Entries in the Apple Event Dispatch Tables,” which begins on page 2-63. You must also write handlers for each Apple event; this section describes how to write these handlers.
Required Apple Events
When a user opens or prints a file from the Finder, the Finder sets up the information your application uses to determine which files to open or print. In system software version 7.0, if your application supports high-level events, the Finder communicates this information to your application through the required Apple events.
The Finder sends one of the required Apple events to your application to ask your application to open or print a list of documents, ask your application to perform the tasks required when a user opens it without opening or printing any documents, or inform your application that the Finder is about to terminate it.
These are the required Apple events:
Apple event Requested action
Open Application Perform tasks your application normally performs
when a user opens your application without opening
or printing any documents
Open Documents Open the specified documents
Print Documents Print the specified documents
Quit Application Perform tasks—such as releasing memory, requesting
the user to save documents, and so on—associated
with quitting; the Finder sends this event to an
application immediately after sending it a Print
Documents event (unless the application was already
open) or if the user chooses Restart or Shut Down
from the Finder’s Special menu
The Finder uses the required Apple events as part of the new mechanisms in system software version 7.0 for launching and terminating applications. This new method of communicating Finder information to your application replaces the mechanisms used in earlier versions of system software.
Applications that do not support high-level events can still use the CountAppFiles, GetAppFiles, and ClrAppFiles procedures (or the GetAppParms procedure) to get the Finder information. See the chapter “The Segment Loader” in Inside Macintosh: Operating System for information on these routines. To make your application 7.0-friendly and compatible with earlier versions of system software, it must support both the old and new mechanisms.
Use the Gestalt function to determine whether the Apple Event Manager is present. If it is and the isHighLevelEventAware flag is set in your application’s 'SIZE' resource, your application receives the Finder information through the required Apple events.
If your application accepts high-level events, it must be able to process the four required Apple events—Open Application, Open Documents, Print Documents, or Quit Application—that the Finder sends in response to actions that the user performs from the desktop.
Your application receives the required Apple events from the Finder in these situations:
n If your application is not open and the user opens your application from the Finder without opening or printing any documents, the Finder launches your application and sends it the Open Application event.
n If your application is not open and the user opens one of your application’s documents from the Finder, the Finder launches your application and sends it the Open Documents event.
n If your application is not open and the user prints one of your application’s documents from the Finder, the Finder launches your application and sends it the Print Documents event. Your application should print the selected documents and remain open until it receives a Quit event from the Finder.
n If your application is open and the user opens or prints any of your application’s documents from the Finder, the Finder sends your application the Open Documents or Print Documents event.
n If your application is open and the user chooses Restart or Shut Down from the Finder’s Special menu, the Finder sends your application the Quit event.
This section describes the required Apple events as they are sent by the Finder. When sent by other applications or processes, these same Apple events—which are among the core Apple events described in the Apple Event Registry: Standard Suites—can include optional parameters not listed here. To be 7.0-friendly, your application only needs to handle the required parameters that are described in this section.<36pt\>\x12 <8bat\>u
Upon receiving any of the required Apple events, your application should perform the action requested by the event. Here is a summary of the contents of the required events and the actions they request applications to perform:
Open Application—perform tasks associated with opening an application
Event class kCoreEventClass
Event ID kAEOpenApplication
Parameters None
Requested action Perform any tasks—such as opening an untitled
document window—that you would normally
perform when a user opens your application without
opening or printing any documents.
Open Documents—open the specified documents
Event class kCoreEventClass
Event ID kAEOpenDocuments
Required parameter
Keyword: keyDirectObject
Descriptor type: typeAEList
Data: A list of alias records for the documents to be opened
Requested action Open the documents specified in the
keyDirectObject parameter.
Print Documents—print the specified documents
Event class kCoreEventClass
Event ID kAEPrintDocuments
Required parameter
Keyword: keyDirectObject
Descriptor type: typeAEList
Data: A list of alias records for the documents to be printed
Requested action Print the documents specified in the
keyDirectObject parameter without opening
windows for the documents.
Quit Application—perform tasks associated with quitting
Event class kCoreEventClass
Event ID kAEQuitApplication
Parameters None
Requested action Perform any tasks that your application would
normally perform when the user chooses Quit. Such
tasks typically include asking the user whether to save
save documents that have been changed. When
appropriate, the Finder sends this event to an
application immediately after sending it a Print
Documents event (unless the application was already
open) or if the user chooses Restart or Shut Down
from the Finder’s Special menu.
Your application needs to recognize only two descriptor types to handle the required Apple events: descriptor lists and alias records. The Open Documents event and Print Documents event use descriptor lists to store a list of documents to open. Each document is specified as an alias record in the descriptor list.
You can retrieve the data that specifies the document to open as an alias record, or you can request that the Apple Event Manager coerce the alias record to a file system specification (FSSpec) record. The file system specification record provides a standard method of identifying files in version 7.0. See the chapter “The File Manager” in Inside Macintosh: Operating System for a complete description of how to specify files using file system specification records.
Handling the Open Application Event
When the user opens your application, the Finder uses the Process Manager to launch your application. On startup, your application typically performs any needed initialization, and then begins to process events. If your application supports high-level events, and if the user (or a script) opens your application without selecting any documents to open or print, your application receives the Open Application event.
To handle the Open Application event, your application should do just what the user expects it to do when it is opened. For example, your application might open a new untitled window in response to an Open Application event.
Listing 2-9 shows a handler that processes the Open Application event. This handler first calls an application-defined function called MyGotRequiredParams. This function checks to see if the Apple event contains any required parameters. By definition, the Open Application event should not contain any required parameters so, if the Apple event does contain any, the handler returns an error. Otherwise the handler opens a new document window.
A handler for the Open Application event
FUNCTION MyHandleOApp (theAppleEvent,reply: AppleEvent;
handlerRefcon: LongInt): OSErr;
VAR
myErr: OSErr;
BEGIN
myErr := MyGotRequiredParams(theAppleEvent);
IF myErr <> noErr THEN
MyHandleOApp := myErr
ELSE
BEGIN
DoNew;
MyHandleOApp := noErr;
END;
END;
For a description of the MyGotRequiredParams function, see Listing 2-15 on page 2-95. For information about the reply and handlerRefcon parameters for an Apple event handler, see “Writing Apple Event Handlers” on page 2-93.
Handling the Open Documents Event
To handle the Open Documents event, your application should open the documents that the Open Documents event specifies in its direct parameter. Your application extracts this information and then opens the specified documents.
Listing 2-10 shows a handler for the Open Documents event. The handler illustrates how to open the documents referred to in the direct parameter.
A handler for the Open Documents event
FUNCTION MyHandleODoc (theAppleEvent,reply: AppleEvent;
handlerRefcon: LongInt): OSErr;
VAR
myFSS: FSSpec;
docList: AEDescList;
myErr: OSErr;
index, itemsInList: LongInt;
actualSize: Size;
keywd: AEKeyword;
returnedType: DescType;
BEGIN
{get the direct parameter--a descriptor list--and put it }
The handler in Listing 2-10 first uses the AEGetParamDesc function to get the direct parameter (specified by the keyDirectObject keyword) out of the Apple event. The handler requests that AEGetParamDesc return a descriptor list in the docList variable. The handler then checks to make sure that it has retrieved all of the required parameters by calling the MyGotRequiredParams function. (See Listing 2-15 on page 2-95 for a description of this function.)
Once the handler has retrieved the descriptor list from the Apple event, it uses AECountItems to count the number of descriptors in the list. Using the returned number as an index, the handler can get the data of each descriptor record in the list. This handler requests that the AEGetNthPtr function coerce the data in the descriptor record to a file system specification record. The handler can then use the file system specification record as a parameter to its own routine for opening files.
For more information on the AEGetParamDesc function, see “Getting Data Out of an Apple Event Parameter” on page 2-87. For more information on the AEGetNthPtr and AECountItems functions, see “Getting Data Out of a Descriptor List” on page 2-91.
After extracting the file system specification record that describes the document to open, your application can use this record to open the file. For example, in Listing 2-10, the code passes the file system specification record to its routine for opening files, the MyOpenFile function.
The MyOpenFile function should be designed so that it can be called both in response to the Open Documents event and to events generated by the user. For example, when the user chooses Open from the File menu, the code that handles the mouse-down event uses the StandardGetFile procedure to let the user choose a file; it then calls MyOpenFile, passing the file system specification record returned by StandardGetFile. By isolating code that performs a requested action from code that interacts with the user, you can easily adapt your application to handle Apple events that request the same action.
Note that your handler should use the AEDisposeDesc function to dispose of the descriptor list when your handler no longer requires the data in it. Your handler should also return a result code.
Handling the Print Documents Event
To handle the Print Documents event, your application should print the documents that the Print Documents event specifies in its direct parameter. Your application extracts this information and then prints the specified documents. Your application should not open any windows for the documents. Also note that your application should remain open after processing the Print Documents event; when appropriate, the Finder sends your application a Quit Application event immediately after sending it a Print Documents event.
Listing 2-11 shows a handler for the Print Documents event. This handler is similar to the handler for the Open Documents event. The code illustrates how to print the documents referred to in the direct parameter.
A handler for the Print Documents event
FUNCTION MyHandlePDoc (theAppleEvent,reply: AppleEvent;
handlerRefcon: LongInt): OSErr;
VAR
myFSS: FSSpec;
docList: AEDescList;
myErr: OSErr;
index, itemsInList: LongInt;
actualSize: Size;
keywd: AEKeyword;
returnedType: DescType;
BEGIN
{get the direct parameter--a descriptor list--and put it }
To handle the Quit Application event, your application should take any actions that are necessary before it is terminated (such as saving any open documents). Listing 2-12 shows an example of a handler for the Quit Application event.
When appropriate, the Finder sends your application a Quit Application event immediately after a Print Documents event. The Finder also sends your application a Quit Application event if the user chooses Restart or Shut Down from the Finder’s Special menu.
A handler for the Quit Application event
FUNCTION MyHandleQuit (theAppleEvent,reply: AppleEvent;
handlerRefcon: LongInt): OSErr;
VAR
userCanceled: Boolean;
myErr: OSErr;
BEGIN
{check for missing required parameters}
myErr := MyGotRequiredParams(theAppleEvent);
IF myErr <> noErr THEN {an error occurred}
BEGIN
{do the necessary error handling}
MyHandleQuit := myErr;
Exit (MyHandleQuit);
END;
userCanceled := MyPrepareToTerminate;
IF userCanceled THEN
MyHandleQuit := userCanceledErr
ELSE
MyHandleQuit := noErr;
END;
The handler in Listing 2-12 calls another function supplied by the application, the MyPrepareToTerminate function. This function saves the documents for any open windows and returns a Boolean value that indicates whether the Quit request was canceled by the user. This is another example of isolating code for interacting with the user from the code that performs the requested action. Structuring your application in this way allows your application to use the same routine when responding to a user event (such as choosing the Quit command from the File menu) or to the corresponding Apple event. (For a description of the MyGotRequiredParams function, see “Writing Apple Event Handlers,” which begins on page 2-93.)
When your application is ready to quit, it should call the ExitToShell procedure from the main event loop, not from your handler for the Quit Application event. Your application should quit only after the handler returns noErr as its function result.
Handling Apple Events Sent by the Edition Manager
If your application provides publish and subscribe capabilities, it should handle the Apple events sent by the Edition Manager in addition to the required Apple events. Your application should also handle the Create Publisher event, which is described in the next section.
The Edition Manager sends your application Apple events to communicate information about the publishers and subscribers in your application’s documents. Specifically, the Edition Manager uses Apple events to notify your application
n when the information in an edition is updated
n when your application needs to write the data from a publisher to an edition
n when your application should locate a particular publisher and scroll through the document to that location
The Apple events sent by the Edition Manager to your application are the Section Read event, Section Write event, and Section Scroll event.
Section Read—read information into the specified section
Event class SectionEventMsgClass
Event ID SectionReadMsgID
Required parameter
Keyword: keyDirectObject
Descriptor type: typeSectionH
Data: A handle to the section record of the subscriber
whose edition contains updated information
Requested action Update the subscriber with the new information from
the edition.
Section Write—write the specified section to an edition
Event class SectionEventMsgClass
Event ID SectionWriteMsgID
Required parameter
Keyword: keyDirectObject
Descriptor type: typeSectionH
Data: A handle to the section record of the publisher
Requested action Write the publisher’s data to its edition.
Section Scroll—scroll through the document to the specified section
Event class SectionEventMsgClass
Event ID SectionScrollMsgID
Required parameter
Keyword: keyDirectObject
Descriptor type: typeSectionH
Data: A handle to the section record of the publisher to
scroll to
Requested actio n Scroll the document to the publisher identified by the
specified section record.
See the chapter “The Edition Manager” in this book for details on how your application should respond to these events.
Handling the Create Publisher Event
If your application supports publish and subscribe capabilities, it should also handle the Create Publisher event.
Create Publisher—create a publisher
Event class kAEMiscStdSuite
Event ID kAECreatePublisher
Required parameter None
Optional parameter
Keyword: keyDirectObject
Descriptor type: typeObjectSpecifier
Data: An object specifier record that specifies the Apple
event object or objects to publish. If this parameter
is omitted, publish the current selection.
Optional parameter
Keyword: keyAEEditionFileLoc
Descriptor type: typeAlias
Data: An alias record that contains the location of the
edition container to create. If this parameter is
omitted, use the default edition container.
Requested action Create a publisher for the specified data using the
specified location for the edition container. If the
data isn’t specified, publish the current selection. If
the location of the edition isn’t specified, use the
default location.
When your application receives the Create Publisher event, it should create a publisher and write the publisher’s data to an edition. The data of the publisher, and the location and name of the edition, are defined by the Apple event. If the Create Publisher event includes a keyDirectObject parameter, then your application should publish the data contained in the parameter. If the keyDirectObject parameter is missing, then your application should publish the current selection. If the document doesn’t have a current selection, your handler for the event should return a nonzero result code.
If the Create Publisher event includes a keyAEEditionFileLoc parameter, your application should use the location and name contained in the parameter as the default location and name of the edition. If the keyAEEditionFileLoc parameter is missing, your application should use the default location and name your application normally uses to specify the edition container.
Listing 2-13 shows a handler for the Create Publisher event. This handler checks for the keyDirectObject parameter and the keyAEEditionFileLoc parameter. If either of these is not specified, the handler uses default values. The handler uses the application-defined function DoNewPublisher function to create the publisher and its edition, create a section record, and update other data structures associated with the document. See the chapter “The Edition Manager” for an example of the DoNewPublisher function.
Note that the handler uses the AEInteractWithUser function to determine whether user interaction is allowed. If user interaction is allowed, the handler sets the promptForDialog variable to TRUE, indicating that the DoNewPublisher function should display the publisher dialog box. If user interaction is not allowed, the handler sets the promptForDialog variable to FALSE, and the DoNewPublisher function does not prompt the user for the location or name of the edition.
A handler for the Create Publisher event
FUNCTION MyHandleCreatePublisherEvent (theAppleEvent,reply:
{add keyErrorNumber and keyErrorString parameters if desired}
MyHandleCreatePublisherEvent := myErr;
END;
Getting Data Out of an Apple Event
The Apple Event Manager stores the parameters and attributes of an Apple event in a format that is internal to the Apple Event Manager. You use Apple Event Manager functions to retrieve the data from an Apple event and return it to your application in a format your application can use.
The Apple Event Manager provides functions that retrieve data from Apple event parameters and attributes. Most of these functions are available in two forms: one that returns the desired data in a specified buffer and one that returns a descriptor record containing the same data. For example, the AEGetParamPtr function uses a specified buffer to return the data contained in an Apple event parameter, and the AEGetParamDesc function returns the descriptor record for a specified parameter.
You can also use Apple Event Manager functions to get data out of descriptor records, descriptor lists, and AE records. You use similar functions to put data into descriptor records, descriptor lists, and AE records.
When your handler receives an Apple event, you typically use the AEGetParamPtr, AEGetAttributePtr, AEGetParamDesc, or AEGetAttributeDesc function to get the data out of the Apple event.
Some Apple Event Manager functions let your application request that the data be returned using any descriptor type, even if it is different from the original descriptor type. If the original data is of a different descriptor type, the Apple Event Manager attempts to coerce the data to the requested descriptor type.
For example, the AEGetParamPtr function lets you specify the desired descriptor type of the resulting data as follows:
In this example, the desired type is specified in the third parameter by the typeLongInteger descriptor type. This requests that the Apple Event Manager coerce the data to a long integer if it is not already of this type.
To ensure that no coercion is performed and that the descriptor type of the result is of the same type as the original, you can specify typeWildCard for the desired descriptor type.
The Apple Event Manager returns the descriptor type of the resulting data in the returnedType parameter. This is useful information when you specify typeWildCard as the desired descriptor type; you can determine the descriptor type of the resulting data by examining this parameter.
The Apple Event Manager can coerce many different types of data. For example, the Apple Event Manager can convert alias records to file system specification records, integers to Boolean data types, and characters to numeric data types, in addition to other data type conversions. For a complete list of the data types for which the Apple Event Manager provides coercion handling, see Table 2-1 on page 2-156.
To perform data coercions that the Apple Event Manager doesn’t perform, you can provide your own coercion handlers. See “Writing and Installing Coercion Handlers,” which begins on page 2-153, for information on providing your own coercion handlers.
Apple event parameters are keyword-specified descriptor records. You can use AEGetParamDesc to get the descriptor record of a parameter, or you can use AEGetParamPtr to get the data out of the descriptor record of a parameter. If an Apple event parameter consists of an object specifier record, you can use AEResolve and your own object accessor functions to resolve the object specifier record—that is, to locate the Apple event object it describes. For more information about AEResolve and object accessor functions, see “Writing Object Accessor Functions,” which begins on page 2-157. Attributes are also keyword-specified descriptor records, and you can use similar routines to get the descriptor record of an attribute or to get the data out of an attribute.
The following sections show how to use the AEGetParamPtr, AEGetAttributePtr, AEGetParamDesc, or AEGetAttributeDesc function to get the data out of an Apple event.
Getting Data Out of an Apple Event Parameter
You can use the AEGetParamPtr or AEGetParamDesc function to get the data out of an Apple event parameter. Use the AEGetParamPtr function (or the AEGetKeyPtr function, which works the same way) to return the data contained in a parameter. Use the AEGetParamDesc function when you need to get the descriptor record of a parameter or to extract the descriptor list from a parameter.
For example, you use an Apple Event Manager function to get the data out of a Section Read event. The Edition Manager sends your application a Section Read event to tell your application to read updated information from an edition into the specified subscriber. The direct parameter of the Apple event contains a handle to the section record of the subscriber. You can use the AEGetParamPtr function to get the data out of the Apple event.
You specify the Apple event that contains the desired parameter, the keyword of the desired parameter, the descriptor type the function should use to return the data, a buffer to store the data, and the size of this buffer as parameters to the AEGetParamPtr function. The AEGetParamPtr function returns the descriptor type of the resulting data and the actual size of the data, and it places the requested data in the specified buffer.
In this example, the keyDirectObject keyword specifies that the AEGetParamPtr function should extract information from the direct parameter; AEGetParamPtr returns the data in the buffer specified by the sectionH variable.
You can request that the Apple Event Manager return the data using the descriptor type of the original data or you can request that the Apple Event Manager coerce the data into a descriptor type that is different from the original. You can specify the desired descriptor type as typeWildCard if you don’t want any coercion performed—in which case, the AEGetParamPtr function returns the original descriptor type of the parameter.
The typeSectionH descriptor type specifies that the returned data should be coerced to a handle to a section record. You can use the information returned in the sectionH variable to identify the subscriber and read in the information from the edition.
In this example, the AEGetParamPtr function returns in the returnedType variable the descriptor type of the resulting data. The descriptor type of the resulting data matches the requested descriptor type unless the Apple Event Manager wasn’t able to coerce the data to the specified descriptor type or you specified the desired descriptor type as typeWildCard. If the coercion fails, the Apple Event Manager returns the errAECoercionFail result code.
The AEGetParamPtr function returns the actual size of the data (that is, the size of coerced data, if any coercion was performed) returned in the actualSize variable. If the value returned in the actualSize variable is greater than the amount your application allocated for the buffer to hold the returned data, your application can increase the size of its buffer to this amount, and get the data again. You can also choose to use the AEGetParamDesc function when your application doesn’t know the size of the data.
In general, use the AEGetParamPtr function to extract data that is of fixed length or known maximum length, and the AEGetParamDesc function to extract data that is of variable length. The AEGetParamDesc function returns the descriptor record for a Apple event parameter. This function is useful, for example, for extracting a descriptor list from a parameter.
You specify the Apple event that contains the desired parameter, the keyword of the desired parameter, the descriptor type the function should use to return the descriptor record, and a buffer to store the returned descriptor record as parameters to the AEGetParamDesc function. The AEGetParamDesc function returns the descriptor record using the specified descriptor type.
For example, the direct parameter of the Open Documents event contains a descriptor list that specifies the documents to open. You can use the AEGetParamDesc function to get the descriptor list out of the direct parameter.
In this example, the Apple event specified by the variable theAppleEvent contains the desired parameter. The keyDirectObject keyword specifies that the AEGetParamDesc function should get the descriptor record of the direct parameter. The typeAEList descriptor type specifies that the descriptor record should be returned as a descriptor list. In this example, the AEGetParamDesc function returns a descriptor list in the docList variable.
The descriptor list contains a list of descriptor records. To get the descriptor records and their data out of a descriptor list, use the AECountItems function to find the number of descriptor records in the list, and then make repetitive calls to the AEGetNthPtr function to get the data out of each descriptor record. See “Getting Data Out of a Descriptor List” on page 2-91 for more information.
Note that the AEGetParamDesc function copies the descriptor record from the parameter. When you’re done with a descriptor record that you obtained from AEGetParamDesc, you must dispose of it by calling the AEDisposeDesc function.
If an Apple event parameter consists of an object specifier record, you can use AEResolve to resolve the object specifier record (that is, locate the Apple event object it describes), as explained in “Resolving Object Specifier Records” on page 2-53.
Getting Data Out of an Attribute
You can use the AEGetAttributePtr or AEGetAttributeDesc function to get the data out of the attributes of an Apple event.
You specify the Apple event that contains the desired attribute, the keyword of the desired attribute, the descriptor type the function should use to return the data, a buffer to store the data, and the size of this buffer as parameters to the AEGetAttributePtr function. The AEGetAttributePtr function returns the descriptor type of the returned data and the actual size of the data, and it places the requested data in the specified buffer.
For example, this code gets the data out of the keyEventSourceAttr attribute of an Apple event:
The keyEventSourceAttr keyword specifies the attribute from which to get the data. The typeShortInteger descriptor type specifies that the data should be returned as a short integer; the returnedType variable contains the actual descriptor type that is returned. You also must specify a buffer to hold the returned data and specify the size of this buffer. If the data is not already a short integer, the Apple Event Manager will coerce it before returning it. The AEGetAttributePtr function returns the actual size of the data returned in the actualSize variable after coercion has taken place. You can check this value to make sure you got all the data.
As with the AEGetParamPtr function, you can request that AEGetAttributePtr return the data using the descriptor type of the original data, or you can request that the Apple Event Manager coerce the data into a descriptor type that is different from the original.
In this example, the AEGetAttributePtr function returns the requested data as a short integer in the sourceOfAE variable, and you can get information about the source of the Apple event by examining this value. You can test the returned value against the values defined by the data type AEEventSource:
TYPE AEEventSource = (kAEUnknownSource, kAEDirectCall,
kAESameProcess, kAELocalProcess,
kAERemoteProcess);
The constants defined by the data type AEEventSource have the following meanings:
Constant Meaning
kAEUnknownSource Source of Apple event unknown
kAEDirectCall A direct call that bypassed the PPC Toolbox
kAESameProcess Target application is also the source application
kAELocalProcess Source application is another process on the same
computer as the target application
kAERemoteProcess Source application is a process on a remote
computer on the network
The next example shows how to use the AEGetAttributePtr function to get data out of the keyMissedKeywordAttr attribute. After your handler extracts all known parameters from an Apple event, it should check whether the keyMissedKeywordAttr attribute exists. If it does, then your handler did not get all of the required parameters.
Note that if AEGetAttributePtr returns the errAEDescNotFound result code, then the keyMissedKeywordAttribute does not exist—which indicates that your application has extracted all of the required parameters. If AEGetAttributePtr returns noErr, then the keyMissedKeywordAttribute does exist—which indicates that your handler did not get all of the required parameters.
The data in the keyMissedKeywordAttr attribute contains the keyword of the first required parameter, if any, that your handler didn’t retrieve. If you want this data returned, specify a buffer to hold the data and specify the size of the buffer. Otherwise, as in this example, specify NIL as the buffer and 0 as the size of the buffer.
This example shows how to use the AEGetAttributePtr function to get the address of the sender of an Apple event from the keyAddressAttr attribute of the Apple event:
The keyAddressAttr keyword specifies the attribute to get the data from. The typeTargetID descriptor type specifies that the data should be returned as a target ID record; the returnedType variable contains the actual descriptor type that is returned. You can examine the address returned in the addressOfAE variable to determine the sender of the Apple event.
The target ID record returned in the addressOfAE variable contains the sender’s port name, port location, and session reference number. To get the process serial number for a process on the local machine, pass the port name returned in the target ID record to the GetProcessSerialNumberFromPortName function. You can then pass the process serial number to the GetProcessInformation function to find the creator signature for a given process.
For more information about target addresses, see “Specifying a Target Address” on page 2-116.
Getting Data Out of a Descriptor List
You can use the AECountItems function to count the number of items in a descriptor list, and you can use AEGetNthDesc or AEGetNthPtr to get a descriptor record or its data out of a descriptor list.
The Open Documents event contains a direct parameter that specifies the list of documents to open. The list of documents is contained in a descriptor list. After extracting the descriptor list from the parameter, you can determine the number of items in the list and then extract each descriptor record from the descriptor list. See Figure 2-8 on page 2-22 for a depiction of the Open Documents event.
For example, when your handler receives an Open Documents event, you can use the AEGetParamDesc function to return the direct parameter as a descriptor list. You can then use AECountItems to return the number of descriptor records in the list.
The AEGetParamDesc function returns in the docList variable the descriptor list from the direct parameter of the Open Documents event. You specify this list to the AECountItems function.
You specify the descriptor list whose items you want to count in the first parameter to AECountItems. The Apple Event Manager returns the number of items in the list in the second parameter. When extracting the descriptor records from a list, you often use the number of items as a loop index. Here’s an example:
FOR index := 1 TO itemsInList DO
BEGIN
{for each descriptor record in the list, get its data}
END;
The format of the descriptor records in a descriptor list is private to the Apple Event Manager. You must use the AEGetNthPtr or AEGetNthDesc function to extract descriptor records from a descriptor list.
You specify the descriptor list that contains the desired descriptor records and an index as parameters to the AEGetNthPtr function. The index represents a specific descriptor record in the descriptor list. AEGetNthPtr returns the data from the descriptor record represented by the specified index.
You also specify the descriptor type the function should use to return the data, a buffer to store the data, and the size of this buffer. If the specified descriptor record exists, the AEGetNthPtr function returns the keyword of the parameter, the descriptor type of the returned data, and the actual size of the data, and it places the requested data in the specified buffer.
Here’s an example that uses the AEGetNthPtr function to extract an item from the descriptor list in the direct parameter of the Open Documents event.
The docList variable specifies the descriptor list from the direct parameter of the Open Documents event. The index variable specifies the index of the descriptor record to extract. You can use the typeFSS descriptor type, as in this example, to specify that the data be returned as a file system specification record. The Apple Event Manager automatically coerces the original data type of the descriptor record from an alias record to a file system specification record. The AEGetNthPtr function returns the keyword of the parameter in the keywd variable. The function returns in the returnedType variable the descriptor type of the resulting data.
You specify a buffer to hold the desired data and the size (in bytes) of the buffer as parameters to the AEGetNthPtr function. In this example, the myFSS variable specifies the buffer. The function returns the actual size of the data in the actualSize variable. If this size is larger than the size of the buffer you provided, you know that you didn’t get all of the data for the descriptor record.
Listing 2-14 shows a more complete example of extracting the items from a descriptor list in the Open Documents event.
For each Apple event your application supports, you must provide a function called an Apple event handler. The AEProcessAppleEvent function calls one of your Apple event handlers when it processes an Apple event. Your Apple event handlers should perform any action requested by the Apple event, add parameters to the reply Apple event if appropriate, and return a result code.
The Apple Event Manager uses dispatch tables to route Apple events to the appropriate Apple event handler. You must supply an Apple event handler for each entry in your application’s Apple event dispatch table. Each handler must be a function that uses this syntax:
FUNCTION MyEventHandler (theAppleEvent: AppleEvent;
reply: AppleEvent;
handlerRefcon: LongInt): OSErr;
The parameter theAppleEvent is the Apple event to handle. Your handler uses Apple Event Manager functions to extract any parameters and attributes from the Apple event and then performs the necessary processing. The reply parameter is the default reply provided by the Apple Event Manager. (“Replying to an Apple Event” on page 2-96 describes how to add parameters to the default reply.) The handlerRefcon parameter is the reference constant stored in the Apple event dispatch table entry for the Apple event. Your handler should pass 0 in this parameter if your application does not use the reference constant.
You can use the reference constant for anything you wish. For example, if you want to handle several Apple events with one handler, you can install entries for each event in your application’s Apple event dispatch table that specify the same handler but different reference constants. Your handler can then use the reference constant to distinguish the different Apple events it handles.
After extracting all known parameters from the Apple event, every handler should determine whether the Apple event contains any further required parameters. Your handler can determine whether it retrieved all the required parameters by checking to see if the keyMissedKeywordAttr attribute exists. If the attribute exists, then your handler has not retrieved all the required parameters and should immediately return an error. If the attribute does not exist, then the Apple event does not contain any more required parameters, although it may contain additional optional parameters.
The Apple Event Manager determines which parameters are optional according to the keywords listed in the keyOptionalKeywordAttr attribute. The source application is responsible for adding keywords for any optional parameters to the keyOptionalKeywordAttr attribute, a source application can choose not to include the keyword for an Apple event parameter even if that parameter is listed in the Apple Event Registry: Standard Suites as an optional parameter. This has the effect of forcing the target application to treat the parameter as required for a particular Apple event. If the target application supports the optional parameter, it should handle the Apple event as the client application expects. If the target application does not support the optional parameter and checks whether it has received all the required parameters, it finds that there’s another parameter that the client application considered required, and should return the result code errAEEventNotHandled.
Listing 2-15 shows a function that checks for a keyMissedKeywordAttr attribute. A handler calls this function after getting all the parameters it knows about from an Apple event.
A function that checks for a keyMissedKeywordAttr attribute
FUNCTION MyGotRequiredParams (theAppleEvent: AppleEvent): OSErr;
VAR
returnedType: DescType;
actualSize: Size;
myErr: OSErr;
BEGIN
myErr := AEGetAttributePtr(theAppleEvent,
keyMissedKeywordAttr,
typeWildCard, returnedType,
NIL, 0, actualSize);
IF myErr = errAEDescNotFound THEN {you got all the required }
{ parameters}
MyGotRequiredParams := noErr
ELSE IF myErr = noErr THEN {you missed a required }
{ parameter}
MyGotRequiredParams := errAEParamMissed
ELSE {the call to }
{ AEGetAttributePtr failed}
MyGotRequiredParams := myErr;
END;
The code in Listing 2-15 uses the AEGetAttributePtr function to get the keyMissedKeywordAttr attribute. This attribute contains the first required parameter, if any, that your handler didn’t retrieve. If AEGetAttributePtr returns the errAEDescNotFound result code, the Apple event doesn’t contain a keyMissedKeywordAttr attribute. If the Apple event doesn’t contain this attribute, then your handler has extracted all of the parameters that the client application considered required.
If the AEGetAttributePtr function returns noErr as the result code, then the attribute does exist, meaning that your handler has not extracted all of the required parameters. In this case, your handler should return an error and not process the Apple event.
The first remaining required parameter is specified by the data of the keyMissedKeywordAttr attribute. If you want this data returned, specify a buffer to hold the data. Otherwise, specify NIL as the buffer and 0 as the size of the buffer. If you specify a buffer to hold the data, you can check the value of the actualSize parameter to see if the data is larger than the buffer you allocated.
For more information about specifying Apple event parameters as optional or required, see “Specifying Optional Parameters for an Apple Event” on page 2-112.
Replying to an Apple Event
Your handler routine for a particular Apple event is responsible for performing the action requested by the Apple event, and can optionally return data in a reply Apple event. The Apple Event Manager passes a default reply Apple event to your handler. The default reply Apple event has no parameters when it is passed to your handler. Your handler can add parameters to the reply Apple event. If the client application requested a reply, the Apple Event Manager returns the reply Apple event to the client.
The reply Apple event is identified by the kCoreEventClass event class and by the kAEAnswer event ID. If the client application specified the kAENoReply flag in the reply parameter of the AESend function, the Apple Event Manager passes a null descriptor record (a descriptor record of type typeNull, which does not contain any data) to your handler instead of a default reply Apple event. Your handler should check the descriptor type of the reply Apple event before attempting to add any attributes or parameters to it. If your handler attempts to add an Apple event attribute or parameter to a null descriptor record, it will generate an error.
If the client application requests a reply, the Apple Event Manager prepares a reply Apple event for the client by passing a default reply Apple event to your handler. If the client application does not request a reply, the Apple Event Manager passes a null descriptor record (a descriptor record of type typeNull, which does not contain any data) to your handler instead of a default reply Apple event. The default reply Apple event has no parameters when it is passed to your handler. Your handler can add any parameters to the reply Apple event. If your application is a spelling checker, for example, you can return a list of misspelled words in a parameter. However, your handler should check the descriptor type of the reply Apple event before attempting to add any attributes or parameters to it. If your handler attempts to add an Apple event attribute or parameter to a null descriptor record, it will generate an error.
When your handler finishes processing an Apple event, it returns a result code to AEProcessAppleEvent. The AEProcessAppleEvent function returns this result code as its function result. If your handler returns a nonzero result code, and if you have not added your own keyErrorNumber parameter, the Apple Event Manager also returns this result code to the client application by putting the result code into a keyErrorNumber parameter for the reply Apple event. The client can check for the existence of this parameter to determine whether the handler performed the requested action.
The client application specifies whether it wants a reply Apple event or not by specifying flags (represented by constants) in the sendMode parameter of the AESend function.
If the client specifies the kAEWaitReply flag in the sendMode parameter, the AESend function does not return until the timeout specified by the timeoutInTicks parameter expires or the server applicatuon returns a reply. When the server application returns a reply, the reply parameter to AESend contains the reply Apple event that your handler returned to the AEProcessAppleEvent function. The client application must dispose of the reply event after it is finished with it; but the Apple Event Manager disposes of the reply event for the server application when the server’s handler returns to AEProcessAppleEvent.
If the client specified the kAEQueueReply flag, the client receives the reply event at a later time during its normal processing of other events.
Your handler should always set its function result to noErr if it successfully handles the Apple event or to a nonzero result code if an error occurs. The Apple Event Manager automatically adds any nonzero result code that your handler returns to a keyErrorNumber parameter in the reply Apple event. In addition to returning a result code, your handler can also return an error string in the keyErrorString parameter of the reply Apple event. Your handler should provide meaningful text in the keyErrorString parameter, so that the client can display this string to the user if desired.
Listing 2-16 shows how to add the keyErrorString parameter to the reply Apple event. See “Adding Parameters to an Apple Event” on page 2-111 for a description of the AEPutParamPtr function.
Adding the keyErrorString parameter to the reply Apple event
FUNCTION MyHandler (theAppleEvent: AppleEvent; reply: AppleEvent;
handlerRefcon: LongInt): OSErr;
VAR
myErr: OSErr;
errStr: Str255;
BEGIN
{if an error occurs when handling an Apple event, set the }
{ function result and error string accordingly}
IF myErr <> noErr THEN
BEGIN
MyHandler := myErr; {result code to be returned--the }
{ Apple Event Manager adds this result }
{ code to the reply Apple event as the }
{ keyErrorNumber parameter}
IF (reply.dataHandle <> NIL AND (myErr = noErr) THEN
{add error string parameter to the default reply}
errStr := 'Why error occurred'; {strings should normally }
If your handler needs to return data to the client, it can add parameters to the reply Apple event. Listing 2-17 shows how a handler for the Multiply event (an imaginary Apple event that asks the server to multiply two numbers) might return the results of the multiplication to the client.
Adding parameters to the reply Apple event
FUNCTION MyMultHandler (theAppleEvent: AppleEvent;
reply: AppleEvent;
handlerRefcon: LongInt): OSErr;
VAR
myErr: OSErr;
number1,number2: LongInt;
replyResult: LongInt;
actualSize: Size;
returnedType: DescType;
BEGIN
{get the numbers to multiply from the parameters of the }
{ Apple event; put the numbers in the number1 and number2
{ variables and then perform the requested multiplication }
myErr := MyDoMultiply(theAppleEvent, number1,
number2, replyResult);
{return result of the multiplication in the reply Apple event}
IF (reply.dataHandle <> NIL AND (myErr = noErr) THEN
BEGIN
myErr := AEPutParamPtr(reply, keyDirectObject,
typeLongInteger, @replyResult,
SizeOf(replyResult));
MyMultHandler := myErr;
END;
{if an error occurs, set the function result and error string }
{ accordingly, as shown in Listing 2-16}
END;
Disposing of Apple Event Data Structures
Whenever you use Apple Event Manager functions to create a descriptor record, descriptor list, or Apple event record, the Apple Event Manager allocates memory for these data structures. Likewise, when you extract a descriptor record by using Apple Event Manager functions, the Apple Event Manager creates a copy of the descriptor record for you to use.
Whenever you finish using a descriptor record or descriptor list that you have created or extracted from an Apple event, you must dispose of the descriptor record—and thereby deallocate the memory it uses—by calling the AEDisposeDesc function.
Also, when you finish using the Apple event specified in the AESend function and have finished with the reply Apple event, you should dispose of their descriptor records using the AEDisposeDesc function. You should dispose of them even if AESend returns a nonzero result code.
Once you finish using them, you should dispose of any Apple event data structures created or returned by these functions:
AECoerceDesc AEDuplicateDesc
AECoercePtr AEGetAttributeDesc
AECreateAppleEvent AEGetKeyDesc
AECreateDesc AEGetNthDesc
AECreateList AEGetParamDesc
If you set the disposeInputs parameter to FALSE for any of the following functions, you should dispose of any Apple event data structures that they create or return:
CreateCompDescriptor CreateRangeDescriptor
CreateLogicalDescriptor CreateObjSpecifier
Even if you add a descriptor record to an Apple event (for example, when you create a descriptor record by calling AECreateDesc and then put a copy of it into a parameter of an Apple event by calling AEPutParamDesc), you are still responsible for disposing of the original descriptor record.
The Apple Event Manager does take care of disposing of the Apple event data structures when your handler returns to AEProcessAppleEvent; in this case, the Apple Event Manager disposes of the Apple event and the reply Apple event. Note that your handler is still responsible for disposing of any Apple event data structures created when extracting data from the Apple event. The Apple event and reply Apple event that your handler receives are only copies of the originals. The client application is responsible for disposing of the original data structures.
Your application is also responsible for disposing of some of the tokens it creates in the process of resolving an object specifier record. For information about token disposal, see “Defining Tokens” on page 2-169.
Interacting With the User
When your application receives an Apple event, it may need to interact with the user. For example, your application may need to display a dialog box asking for additional information or confirmation from the user. You must use the AEInteractWithUser function to make sure your application is in the foreground before it actually interacts with the user.
Both the client application and the server application specify their preferences for user interaction. The AEInteractWithUser function checks the user interaction preferences set by each application. If both the client and the server allow user interaction, AEInteractWithUser usually posts a notification request, and the Notification Manager brings the server to the foreground after the user responds to the notification request.
The AEInteractWithUser function can also bring the server application directly to the foreground, but only if the client application is the active application on the same machine and has set two flags in the sendMode parameter of the AESend function: the kAEWaitReply flag, which indicates that it is waiting for a reply, and the kAECanSwitchLayer flag, which indicates that it wants the server application to come directly to the foreground rather than posting a notification request.
A client application specifies its preferences for how the server application should interact with the user by setting various flags in the sendMode parameter to AESend. The Apple Event Manager sets the corresponding flags in the keyInteractLevelAttr attribute of the Apple event.
The server application sets its preferences with the AESetInteractionAllowed function. This function lets your application specify whether it allows interaction with the user as a result of receiving an Apple event from itself; from itself and other processes on the local machine; or from itself, local processes, and processes from another computer on the network.
Your application calls the AEInteractWithUser function before interacting with the user. If AEInteractWithUser returns the noErr result code, then your application is currently in the front and your application is free to interact with the user. If AEInteractWithUser returns the errAENoUserInteraction result code, the conditions didn’t allow user interaction and your application should not interact with the user.
The rest of this section explains how to set user interactions for the client and server applications and the practical effect of these settings when a server application needs to interact with a user.
Setting the Client Application’s User Interaction Preferences
The client application sets its user interaction preferences by setting flags in the sendMode parameter to the AESend function. The Apple Event Manager automatically adds the specified flags to the keyInteractLevelAttr attribute of the Apple event. These flags are represented by the following constants:
Flag Description
kAENeverInteract The server application should never interact with the
user in response to this Apple event. If this flag is set,
AEInteractWithUser returns the
errAENoUserInteraction result code. This flag is
the default when an Apple event is sent to a remote
application.
kAECanInteract The server application can interact with the user in
response to this Apple event—by convention, if the
user needs to supply information to the server. If this
flag is set and the server allows interaction,
AEInteractWithUser either brings the server
application to the foreground or posts a notification
request. This flag is the default when an Apple event is
sent to a local application.
kAEAlwaysInteract The server application can interact with the user in
response to this Apple event—by convention,
whenever the server application normally asks a user
to confirm a decision or interact in any other way,
even if no additional information is needed from the
user. If this flag is set and the server allows
interaction, AEInteractWithUser either brings the
server application to the foreground or posts a
notification request.
The interpretation of the kAECanInteract and kAEAlwaysInteract flags depends on the server application only, and is not enforced by the Apple Event Manager. A Print event that specifies a range of pages to print provides a good example of the way these flags should be interpreted by a server application. If the client application sets the kAECanInteract flag before sending the Print event, the server application should not interact with the user, because it doesn’t require any additional information from the user in order to respond to the event. If the client application sets the kAEAlwaysInteract flag, the server application should attempt interact with the user as it normally would if it were the foreground application: that is, by displaying the Print dialog box so the user can confirm the specified range of pages.
If the client application doesn’t specify any of the three user interaction flags, the Apple Event Manager sets either the kAENeverInteract or the kAECanInteract flag in the keyInteractLevelAttr attribute of the Apple event, depending on the location of the server application. If the server application is on a remote computer, the Apple Event Manager sets the kAENeverInteract flag as the default. If the server application is on the local computer, the Apple Event Manager sets the kAECanInteract flag as the default.
In addition to the three user interaction flags, the client application can set another flag in the sendMode parameter to AESend to request that the Apple Event Manager immediately bring the server application directly to the foreground instead of posting a notification request:
Flag Description
kAECanSwitchLayer If both the client and server allow interaction, and if
the client application is the active application on the
local machine and is waiting for a reply (that is, it
has set the kAEWaitReply flag),
AEInteractWithUser brings the server directly to
the foreground. Otherwise, AEInteractWithUser
uses the Notification Manager to request that the
user bring the server application to the foreground.
Note that while the kAECanSwitchLayer flag must be set in order for the Apple Event Manager to bring the server application directly to the foreground, setting it will not, by itself, guarantee that the Apple Event Manager will bypass the notification request if user interaction is permitted. Another flag, the kAEWaitReply flag, must also be set in the sendMode parameter. The kAEWaitReply flag is one of three flags in the sendMode parameter that you can use to specify how your application should wait for a reply. (For a description of these flags, see “Requesting Services Through Apple Events” on page 2-33.) If the client application is not waiting for a reply, the user may have continued with other work, and an application switch might therefore be unexpected and would violate the principle of user control as described in the Human Interface Guidelines.
When a server application calls AEInteractWithUser, the function first checks to see if the kAENeverInteract flag in the keyInteractLevelAttr attribute of the Apple event is set. (The Apple Event Manager sets this attribute according to the flags specified in the sendMode parameter of AESend.) If the kAENeverInteract flag is set, AEInteractWithUser immediately returns the errAENoUserInteraction result code. If the client specified kAECanInteract or kAEAlwaysInteract, AEInteractWithUser checks the server’s preferences for user interaction.
Setting the Server Application’s User Interaction Preferences
The server sets its user interaction preferences by using the AESetInteractionAllowed function. You use this function to tell the Apple Event Manager the processes for which your application is willing to interact with the user.
myErr := AESetInteractionAllowed(level);
The level parameter is of type AEInteractAllowed.
TYPE AEInteractAllowed = (kAEInteractWithSelf,
kAEInteractWithLocal,
kAEInteractWithAll);
You can specify one of these values for the interaction level:
Flag Description
kAEInteractWithSelf User interaction with your server application in
response to an Apple event may be allowed only
when the client application is your own application—
that is, only when your application is sending the
Apple event to itself.
kAEInteractWithLocal User interaction with your server application in
response to an Apple event may be allowed only if the
client application is on the same computer as your
application. This is the default if the server
application does not call the function
AESetInteractionAllowed.
kAEInteractWithAll User interaction with your server application in
response to an Apple event may be allowed for any
client application on any computer.
If the server application does not set the user interaction level, AEInteractWithUser uses kAEInteractWithLocal as the value.
If the application sends itself an Apple event (that is, the application is both the client and the server) without setting the kAENeverInteract flag, AEInteractWithUser always allows user interaction. If the client application is a process on the local machine, and the server set the interaction level to the kAEInteractWithLocal or kAEInteractWithAll flag, then AEInteractWithUser allows user interaction. If the client is a process on a remote computer on the network, AEInteractWithUser allows user interaction only if the server specified the kAEInteractWithAll flag for the interaction level. In all other cases, AEInteractWithUser does not allow user interaction.
Requesting User Interaction
If your server application needs to interact with the user for any reason, it must call the AEInteractWithUser function to make sure it is in the foreground before it actually interacts with the user. When AEInteractWithUser allows user interaction (based on the client’s and server’s preferences), AEInteractWithUser brings the server application to the foreground—either directly or after the user responds to a notification request—and then returns a noErr result code.
The first parameter to the AEInteractWithUser function specifies how long your handler is willing to wait for a response from the user. For example, if the timeout value is 15 seconds and the Apple Event Manager posts a notification request, an icon begin to flash in the upper-right corner of the screen, but it will stop flashing if the user does does not respond within 15 seconds. The icon will be either the server application’s icon or, if the server application specified a notification record as one of the parameters to the AEInteractWIthUser function, the icon specified in the notification record. Note that the timeout value passed to the AEInteractWithUser function is separate from the timeout value passed to the AESend function, which specifies how long the client application is willing to wait for the reply or return receipt from the server application.
If AEInteractWithUser does not receive a response from the user within the specified timeout value, AEInteractWithUser returns the errAETimeout result code.
You may want to give the user a method of setting the interaction level. For example, some users may not want to be interrupted while background processing of an Apple event occurs, or they may not want to respond to dialog boxes when your application is handling Apple events sent from another computer.
Listing 2-18 illustrates the use of the AEInteractWithUser function. You call this function before your application displays a dialog box or otherwise interacts with the user when processing an Apple event. You specify a timeout value, a pointer to a Notification Manager record, and the address of an idle function as parameters to AEInteractWithUser.
{the attempt to interact failed; do any error handling}
DoError(myErr)
ELSE
{interact with the user by displaying a dialog box }
{ or by interacting in any other way that is necessary}
DisplayMyDialogBox;
You can set a timeout value, in ticks, in the first parameter to AEInteractWithUser. Use the kAEDefaultTimeout constant if you want the Apple Event Manager to use a default value for the timeout value. The Apple Event Manager uses a timeout value of about one minute if you specify this constant. You can also specify the kNoTimeOut constant if your application is willing to wait an indefinite amount of time for a response from the user. Usually you should provide a timeout value, so that your application can complete processing of the Apple event in a reasonable amount of time.
You can provide a pointer to a Notification Manager record in the second parameter, or you can specify NIL to use the default record provided by AEInteractWithUser. The AEInteractWithUser function only uses a Notification Manager record when user interaction is allowed and the kAECanSwitchLayer flag in the keyInteractLevelAttr attribute is not set.
The last parameter to AEInteractWithUser specifies an idle function provided by your application. Your idle function should handle any update events, null events, operating-system events, or activate events while your application is waiting to be brought to the front. See “Writing an Idle Function” on page 2-150 for more information.
Figure 2-19 illustrates a situation in which a client application might request a service from a server application that requires the server application to interact with the user in order to perform the requested service. In this example, a forms application requests a service from a database application.
A document with a button that triggers a Get Data event
Figure 2-19 shows part of an electronic form used to enter information about an order received by telephone. If the customer has ordered from the company before, the user can quickly retrieve the customer’s address and telephone number by clicking the Retrieve Customer Info button. Clicking this button causes the forms application to send a Get Data event to a database application called GigaBase that is currently open on the same computer. The Get Data event sent by the the forms application, which is the client application for the ensuing transaction, asks GigaBase, which is the server application, to locate the customer’s name in a table of addresses and return the customer’s address. When the forms application receives the return Apple event, it can add the address data to the appropriate fields in the order form.
If GigaBase, as the server application, locates more than one entry for the specified customer name, it will need to interact with the user in order to determine which data to return in the reply Apple event. In order to interact with the user, the server application must be in the foreground, so that it can display a dialog box like the one shown in Figure 2-20.
A server application displaying a dialog box that requests information from the user
Handling user interaction with the kAEWaitReply flag set
Figure 2-21 and Figure 2-22 illustrate two ways of dealing with the situation illustrated in Figure 2-19 and Figure 2-20. Figure 2-21 shows the circumstances in which AEInteractWithUser will bring the server application directly to the front. The client application sets the kAECanInteract, kAECanSwitchLayer, and kAEWaitReply flags in the sendMode parameter of the AESend function when it sends the Get Data event shown in the figure. By setting these flags, the client application indicates that it expects the user to wait until the address appears in the appropriate fields of the electronic form before continuing with any other work. In this case, an automatic layer switch will not surprise the user and will avoid the additional user action required to respond to a notification request.
The server application in Figure 2-21 uses AESetInteractAllowed to set its own interaction level to kAEInteractWithLocal. After calling AEResolve to located the requested data, the server application discovers that there are two addresses that match the name the user typed into the eletronic form. The server application then calls AEInteractWithUser with a timeout value of kAEDefaultTimeOut. AEInterActWithUser brings the server application directly to the foreground and returns a noErr result code. The server application then displays the dialog box shown in Figure 2-20. When the user selects the desired customer and clicks OK in the dialog box, the server application sends the return Apple event to the client application, which returns to the foreground automatically and displays the requested customer information in the appropriate fields.
Figure 2-22 illustrates almost the same Apple event as that shown in Figure 2-21. The only difference is that the client application has set the kAEQueueReply flag instead of the kAEWaitReply flag in the sendMode parameter of the Get Data event, and has not set the kAECanSwitchKLayer flag. This combination of flags indicates that the client application expects the user to continue filling in other parts of the form, such as the items being ordered; the address will just appear after a while, provided there is no duplicate name. In this case, an automatic layer switch would disrupt the user’s work. Instead of bringing the server application directly to the foreground, AEInterActWithUser uses the Notification Manager to post a notification request. After the user has reponded to the request and brought the server application to the front, AEInterActWithUser returns a noErr result code and the server application displays the dialog box shown in Figure 2-20. When the user selects the desired customer and clicks OK in the dialog box, the server application sends the return Apple event to the client application. In this case, the user must bring the client application back to the foreground manually.
Handling user interaction with the kAEQueueReply flag set
Creating an Apple Event
You create an Apple event by using the AECreateAppleEvent function. You supply parameters that specify the event class and event ID, the target address, the return ID, and the transaction ID, and the AECreateAppleEvent function creates and returns an Apple event with the attributes set as your application requested. You should not directly manipulate the contents of the Apple event; rather, use Apple Event Manager functions to add additional attributes or parameters to it.
This example creates an imaginary Multiply event using the AECreateAppleEvent function. You specify the event class, the event ID, the address of the server application, a return ID, a transaction ID, and a buffer to store the returned Apple event as parameters to AECreateAppleEvent.
The event class here is identified by the kArithmeticClass constant and specifies that this event belongs to a specific class of Apple events for arithmetic operations. The event ID specifies the particular Apple event within the class—in this case, an Apple event that performs multiplication.
You specify the target of the Apple event in the third parameter to AECreateAppleEvent. The target address can identify an application on the local computer or another computer on the network. You can specify the address using a target ID record or session reference number. For processes on the local computer, you can also use a process serial number or application signature to specify the address. See “Specifying a Target Address” on page 2-116 for more information.
You specify the return ID of the Apple event in the fourth parameter. The return ID provides a way to associate this Apple event with the server’s reply. The AECreateAppleEvent function assigns the specified return ID value to the keyReturnIDAttr attribute of the Apple event. If a server returns a standard reply Apple event (that is, an event of event class \qaevt\q and event ID \qansr\q) in response to this event, the Apple Event Manager will assign the reply event the same return ID. When you receive a reply Apple event, you can check the keyReturnIDAttr attribute to determine which outstanding Apple event the reply is responding to. You can use the kAutoGenerateReturnID constant to request that the Apple Event Manager generate a return ID that is unique to this session for the Apple event. Otherwise, you are responsible for making it unique.
The fifth parameter specifies the transaction ID attribute of the Apple event. A transaction is a sequence of Apple events that are sent back and forth between the client and server applications, beginning with the client’s initial request for a service. All Apple events that are part of one transaction must have the same transaction ID.
You can use a transaction ID to indicate that an Apple event is one of a sequence of Apple events related to a single transaction. The kAnyTransactionID constant indicates that the Apple event is not part of a transaction.
The AECreateAppleEvent function creates an Apple event with only the specified attributes and no parameters. To add parameters or additional attributes, you can use other Apple Event Manager functions.
Adding Parameters to an Apple Event
You can use the AEPutParamPtr or AEPutParamDesc function to add parameters to an Apple event. When you use either of these functions, the Apple Event Manager adds the specified parameter to the Apple event.
Use the AEPutParamPtr function when you want to add data specified in a buffer as the parameter of an Apple event. You specify the Apple event, the keyword of the parameter to add, the descriptor type, a buffer that contains the data, and the size of this buffer as parameters to the AEPutParamPtr function. The AEPutParamPtr function adds the data to the Apple event as a parameter with the specified keyword.
For example, this code adds a parameter to the Multiply event using the AEPutParamPtr function.
In this example, the Apple Event Manager adds the parameter containing the first number to the specified Apple event.
Use the AEPutParamDesc function to add a descriptor record to an Apple event. The descriptor record you specify must already exist. To create or get a descriptor record, you can use the AECreateDesc, AEDuplicateDesc, and other Apple Event Manager functions that return a descriptor record.
You specify the descriptor type, a buffer that contains the data, and the size of this buffer as parameters to the AECreateDesc function. The AECreateDesc function returns the descriptor record that describes the data.
This example creates a descriptor record for the second parameter of the Multiply event:
In this example, the AECreateDesc function creates a descriptor record with the typeLongInteger descriptor type and the data identified in the number2 variable.
Once you have created a descriptor record, you can use AEPutParamDesc to add the data to an Apple event parameter. You specify the Apple event to add the parameter to, the keyword of the parameter, and the descriptor record of the parameter as parameters to the AEPutParamDesc function.
This example adds a second parameter to the Multiply event using the AEPutParamDesc function.
This example adds the keyOperand2 keyword and the descriptor record created in the previous example as the second parameter to the specified Apple event.
You can also create a descriptor record without using Apple Event Manager routines. For example, this example generates an alias descriptor record from an existing alias handle:
WITH myAliasDescDo
BEGIN
descriptorType := typeAlias;
dataHandle := myAliasHandle;
END;
Whatever method you use to create a descriptor record, you can add it to an Apple event parameter by using AEPutParamDesc.
After adding parameters to an Apple event, you can send the Apple event using the AESend function. See “Sending an Apple Event” on page 2-143 for information on using this function.
Specifying Optional Parameters for an Apple Event
The parameters for a given Apple event are listed in the Apple Event Registry: Standard Suites as either required parameters or optional parameters. When sending an Apple event, your application should include all of the parameters that are listed as required. Your application does not normally have to include Apple event parameters that are listed as optional; the target application uses default values for optional parameters if your application does not provide them. The Apple Event Registry: Standard Suites defines the default value a target application should use for each optional parameter of a specific Apple event.
For example, the definition of the Create Publisher event includes an optional parameter that specifies the Apple event object to publish. If this parameter is omitted, the target application creates a publisher for the current selection. The definition of the Create Publisher event also includes an optional parameter that specifies the location of the edition container to create. If this parameter is omitted, the target application uses the location specified in the application’s default edition container.
Your application adds optional parameters to an Apple event the same way it adds required parameters, using the AECreateDesc, AEPutParamPtr, and AEPutParamDesc functions as described in the previous section, “Adding Parameters to an Apple Event.” The Apple Event Manager does not automatically keep track of which parameters are optional and which are required. Instead, the source application indicates which Apple event parameters it considers optional by listing the keywords for those parameters in the keyOptionalKeywordAttr attribute.
The keyOptionalKeywordAttr attribute does not contain the optional parameters; it simply lists the keywords of any parameters for the Apple event that the source application wants to identify as optional. Although the source application is responsible for providing this information in the keyOptionalKeywordAttr attribute of an Apple event, it is not required to provide this attribute.
If a keyword for an Apple event parameter is not included in the keyOptionalKeywordAttr attribute, the source application expects the target application to accept the Apple event parameter identified by that keyword. If a target application cannot accept the parameter, it should return the result code errAEEventNotHandled. If a target application cannot accept a parameter whose keyword is listed in the keyOptionalKeywordAttr attribute, it should ignore that parameter and attempt to handle the Apple event as it normally does.
A source application can choose not to list the keyword for an Apple event parameter in the keyOptionalKeywordAttr attribute even if that parameter is listed in the Apple Event Registry: Standard Suites as an optional parameter. This has the effect of forcing the target application to treat the parameter as required for a particular Apple event. If the target application supports the parameter, it should handle the Apple event as the client application expects. If the target application does not support the parameter and calls an application-defined routine such as MyGotRequiredParams to check whether it has received all the required parameters, it finds that there’s another parameter that the client application considered required, and should return the result code errAEEventNotHandled.
If a source application wants a target application to attempt to handle an Apple event regardless of whether the target application supports a particular Apple event parameter included in that Apple event, the source application should list the keyword for that parameter in the keyOptionalKeywordAttr attribute.
It is up to the source application to decide whether to list a parameter that is described as optional in the Apple Event Registry: Standard Suites in the keyOptionalKeywordAttr attribute of an Apple event. For example, if the definition of the Print Documents event were extended to include an optional keyPageRange parameter that specifies a page range, the source application might decide whether or not to list the keyword keyPageRange in the keyOptionalKeywordAttr attribute according to the characteristics of the print request. If the source application were attempting to print only three pages of a 500-page document, it could choose not to add the keyword keyPageRange to the keyOptionalKeywordAttr attribute; in this case, only target applications that supported the keyPageRange parameter would attempt to handle the event. If the source application were attempting to print one page of a one-page document, it could choose to add the keyword keyPageRange to the keyOptionalKeywordAttr attribute; in this case, it would get the same result regardless of whether the target application supported the keyPageRange parameter.
If your application chooses to provide the keyOptionalKeywordAttr attribute for an Apple event, it should first create a descriptor list that specifies the keywords of the optional parameters, then add it to the Apple event as a keyOptionalKeywordAttr attribute.
Listing 2-19 shows an application-defined routine, MyCreateOptionalKeyword, that creates the keyOptionalKeywordAttr attribute for the Create Publisher event.
Creating the optional keyword for the Create Publisher event
FUNCTION MyCreateOptionalKeyword(createPubAppleEvent: AppleEvent)
: OSErr;
VAR
optionalList: AEDescList;
myErr: OSErr;
BEGIN
{create an empty descriptor list}
myErr := AECreateList(NIL, O, FALSE, @optionalList);
{add the keywords for the optional parameters to the list}
myErr := AEPutPtr(&optionalList, 1, 'keyw',
keyDirectObject, sizeOf(keyDirectObject));
myErr := AEPutPtr(&optionalList, 2, 'keyw',
keyAEEditionFileLoc,
sizeOf(keyAEEditionFileLoc));
{create the keyOptionalKeywordAttr attribute and add it }
{ to the Create Publisher event}
myErr := AEPutAttributeDesc(createPubAppleEvent,
keyOptionalKeywordAttr,
@optionalList);
MyCreateOptionalKeyword := myErr;
{add your own error checking}
END;
The MyCreateOptionalKeyword function shown in Listing 2-19 adds the keyword of each parameter that the source application considers optional to a descriptor list as a descriptor record with the descriptor type 'keyw' and data that consists of a keyword. The function specifies that the target application does not need to support parameters identified by the keywords keyDirectObject and keyAEEditionFileLoc in order to handle the Create Publisher event. (These are the parameters that specify the Apple event object to publish and the location of the edition container.) After adding these keywords to the descriptor list, the function creates the keyOptionalKeywordAttr attribute using the AEPutAttributeDesc function.
Typically a target application does not examine the keyOptionalKeywordAttr attribute directly. Instead, a target application that supports a parameter that’s listed in the Apple Event Registry: Standard Suites as optional attempts to extract the parameter from the Apple event (using AEGetParamDesc, for example); if it can’t extract the parameter, it uses the default value, if any, listed in the Apple Event Registry. A target application can use the keyMissedKeywordAttr attribute to return the first required parameter (that is, considered required by the source application), if any, that it did not retrieve from the Apple event. The keyMissedKeywordAttr attribute does not return any parameters whose keywords are listed in the keyOptionalKeywordAttr attribute of the Apple event.
Specifying a Target Address
When you create an Apple event, you must specify the address of the target. The target address identifies the particular application or process to which you want to send the Apple event. You can send Apple events to applications on the local machine or on remote computers on the network.
These are the descriptor types that identify the four methods of addressing an Apple event.
typeApplSignature The application signature of the target
typeSessionID The session reference number of the target
typeTargetID The target ID record of the target
typeProcessSerialNumber The process serial number of the target
To address an Apple event to a target on a remote computer on the network, you must use either the typeSessionID or typeTargetID descriptor type.
If your application sends an Apple event to itself, it should address the Apple event using a process serial number. Use the kCurrentProcess constant to specify the process serial number of your application. This is the fastest way for your application to send an Apple event to itself.
You can use any of the four address types when sending an Apple event to another application on the local computer. The chapter “The Event Manager” in Inside Macintosh: Macintosh Toolbox describes all four types of addresses.
To allow the user to choose the target of an Apple event, use the PPCBrowser function. The PPCBrowser function presents a standard user interface for choosing a target application, much as the Standard File Package provides a standard user interface for opening and saving files. The PPCBrowser function returns information about the application the user chose in a target ID record. (Listing 2-21 on page 2-118 shows how to use the PPCBrowser function to let the user choose a target.)
You specify the address using an address descriptor record (a descriptor record of data type AEAddressDesc). You must create a descriptor record of this type and then add it to the Apple event using the AECreateAppleEvent function.
You can use the AECreateDesc function to create address descriptor records for any of the four types of target addresses. Listing 2-20 shows four possible ways to create an address, each using a different address type.
You specify the descriptor type for the address, a pointer to the buffer containing the address, and the size of the buffer to the AECreateDesc function to create an address descriptor record. The AECreateDesc function returns an address descriptor record with the specified characteristics.
After creating an address, you can specify the address in the AECreateAppleEvent function. See “Creating an Apple Event” on page 2-110 for an example using the AECreateAppleEvent function.
When you specify an address to the AECreateAppleEvent function, the Apple Event Manager stores the address in the keyAddressAttr attribute of the Apple event.
If you use the PPCBrowser function to allow the user to choose an Apple event’s target, your application must create a target ID record based on the user’s choice. Listing 2-21 shows how to create a target ID record using the information returned from the PPCBrowser function and create an address descriptor record using the AECreateDesc function.
Specifying a target address in an Apple event by using the PPCBrowser function
FUNCTION GetTargetAddress (myPrompt: Str255; myAppStr: Str255;
VAR myPortInfo: PortInfoRec;
VAR targetAddress: AEAddressDesc;
VAR toTargetID: targetID): OSErr;
VAR
myErr: OSErr;
BEGIN {use PPCBrowser to let user choose the target}
myErr := PPCBrowser(myPrompt, myAppStr, FALSE,
toTargetID.location, myPortInfo, NIL, '');
IF myErr <> noErr THEN
DoError(myErr)
ELSE
BEGIN
toTargetID.name := myPortInfo.name;
{create the descriptor record for the target address}
myErr := AECreateDesc(typeTargetID, @toTargetID,
SizeOf(toTargetID), targetAddress);
IF myErr <> noErr THEN
DoError(myErr);
END;
GetTargetAddress := myErr;
{add your own error checking}
END;
See the chapter “The Program-to-Program Communications Toolbox” in this book for more information on using the PPCBrowser function.
Creating an Object Specifier Record
If your application requests a service that requires the target application to locate an Apple event object, your application must include an object specifier record describing the Apple event object as a parameter of the Apple event used to request the service. This section describes how to use the four keyword-specified descriptor records introduced in “Working With Object Specifier Records,” which begins on page 2-38, to specify the class ID, container, key form, and key data for an object specifier record. You need to read this section only if your application supports the Core suite or any of the functional-area suites in the Apple Event Registry: Standard Suites.
Your application does not need to create object specifier records in order to respond to the standard Apple events or to be scriptable—that is, capable of responding to scripts written in a scripting language. However, you need to know how object specifier records are constructed in order to write object accessor functions for your application. For an overview of the way the Apple Event Manager works with object accessor functions to resolve object specifier records, see “Resolving Object Specifier Records,” which begins on page 2-53.
Since the internal structure of an object specifier record is nearly identical to the internal structure of an AE record, it is possible to use AECreateList, AEPutPtr, and AEPutKeyDesc to add the four keyword-specified descriptor records to an AE record, then use AECoerceDesc to coerce the AE record to a descriptor record of type typeObjectSpecifier. However, it is usually preferable to use the CreateObjSpecifier function to accomplish the same goal. The CreateObjSpecifier function adds the keyword-specified descriptor records directly to an object specifier record, thus eliminating several steps that are required if you create an AE record first. The instructions that follow make use of CreateObjSpecifier.
To specify the class ID for an object specifier record, your application must create a keyword-specified descriptor record with the keyword keyAEDesiredClass that contains the appropriate object class ID. You can specify the object class ID as the first parameter to the CreateObjSpecifier function, which uses it to create a keyword-specified descriptor record with the keyword keyAEDesiredClass as part of an object specifier record.
To specify the container for an object specifier record, your application must create a keyword-specified descriptor record with the keyword keyAEContainer that fully describes the container of the Apple event object. Since the container for an Apple event object is usually another Apple event object, the container is usually specified by another object specifier record. The ability to nest one object specifier record within another in this way makes it possible to identify a chain of containers that fully describes the location of one or more Apple event objects.
To specify the complete container hierarchy of an Apple event object, your application must create a series of nested object specifier records, starting with the object specifier record for the Apple event object whose container is the outermost container. With the exception of this first object specifier record, each object specifier record specifies another object specifier record in the chain as a container. For example, Figure 2-23 shows a series of nesting object specifier records that specify the first row of a table named “Summary of Sales, 1991” in a document named “Sales Report.” The container specified for the object specifier record on the right side of the figure describes the outermost container in the container hierarchy—the container for the document “Sales Report.”
Nesting object specifier records that specify a container hierarchy
Since a container must be specified for each Apple event object in a container hierarchy, a special descriptor record called the null descriptor record is always used to represent the outermost container. A null descriptor record is a descriptor record whose descriptor type is typeNull and whose data is a NIL handle. A null descriptor record used in a keyword-specified descriptor record with the keyword keyAEContainer specifies an application’s default container, the outermost container for any container hierarchy in that application.
In Figure 2-23, the object specifier record for the document on the right side of the figure uses a null descriptor record to specify the document’s container—that is, the default container for the SurfWriter application. The object specifier record for the document identifies it as the document with the name “Sales Report”; the object specifier record for the table identifies it as the table named “Summary of Sales, 1991” in the document “Sales Report”; and the object specifier record for the row identifies it as the first row of the table named “Summary of Sales, 1991” in the document “Sales Report.”
To specify the default container for an object specifier record, you can use AECreateDesc to create a null descriptor record, which you can then pass as the second parameter to the CreateObjSpecifier function. CreateObjSpecifier uses this descriptor record to create a keyword-specified descriptor record with the keyword keyAEContainer as part of an object specifier record.
The object specifier record that specifies the default container is always the first record you create in a series of nested object specifier records that specifies the complete container hierarchy for an Apple event object. Each of the other object specifier records in the chain (moving from right to left in Figure 2-23) uses the previously created object specifier record to specify its container. As with the null descriptor record, you can pass an object specifier record as the second parameter to the CreateObjSpecifier function, which uses it to create a keyword-specified descriptor record with the keyword keyAEContainer.
In addition to descriptor records of typeNull and typeObjectSpecifier, you can use descriptor records of type typeObjectBeingExamined and type typeCurrentContainer to specify an Apple event object’s container. For more information about these descriptor types, which are used to specify tests and ranges, respectively, see “Creating a Complex Object Specifier Record” on page 2-128.<36pt\>\x12 <8bat\>u
To specify the key form for an object specifier record, your application must create a keyword-specified descriptor record with the keyword keyAEKeyForm that contains a constant describing the form of the key data. For example, the object specifier records in Figure 2-23 that specify the document and the table each have a key form of formName, which means that the key data identifies the document and the table by their names, “Sales Report” and “Summary of Sales, 1991,” respectively. Similarly, the object specifier record in Figure 2-23 that specifies the first row in the table has a key form of formAbsolutePosition, which means that the key data identifies the position of the row compared to other rows in the same container.
You can specify a key form constant as the third parameter to the CreateObjSpecifier function, which uses the specified key form to create a keyword-specified descriptor record with the keyword keyAEKeyForm as part of an object specifier record.
Your application can support either simple or complex object specifier records. A simple object specifier record can specify one element in a container by absolute position, by name, or as a property of the container. A complex object specifier record can specify one element using any of the methods available to a simple object specifier record, and can also specify complex tests, ranges, and relative positions to identify groups of related elements.
Simple object specifier records can specify one of the following key forms:
Key form Corresponding key data
formPropertyID The property ID for an element’s property; for example, pStyle or pFont
formName The value of an element’s name; for example, "MyDoc"
formAbsolutePosition The position of an element in relation to the beginning or end of its container; for example, the fifth word in a paragraph
If you need to specify Apple event objects in a more sophisticated manner, you must use a complex object specifier record, which can specify one of the following key forms:
Key form Corresponding key data
formPropertyID Specifies the property ID for an element’s property; for example, pStyle or pFont.
formName Specifies the value of an element’s name; for example, "Sales Report" .
formAbsolutePosition Specifies the position of one or more elements in relation to the beginning or end of their container; for example, the fifth word in a paragraph, or all the words in a paragraph.
formRelativePosition Specifies an element immediately before or after another element; for example, the word after the third paragraph.
formTest Specifies one or more elements that pass a test. Values of one or more properties or elements can be tested; for example, the first paragraph that is centered and begins with the word “Wild.”
formRange Specifies a list of elements between two other elements; for example, the words between “Green” and “Blue,” inclusive.
To specify the key data for an object specifier record, your application must create a keyword-specified descriptor record with the keyword keyAEKeyData that contains the appropriate data for the specified key form. For simple object specifier records, the key data consists of the name of property, the name of an Apple event object, or a number indicating absolute position, which require descriptor records of type typeType, typeText, or typeLongInteger, respectively. You can use AECreateDesc to create the descriptor record, which you can then specify as the fourth parameter for the CreateObjSpecifier function. CreateObjSpecifier uses this descriptor record to create a keyword-specified descriptor record with the keyword keyAEKeyData as part of an object specifier record.
For complex object specifier records, the key data usually consists of several interconnected descriptor records that collectively define a relative position, a test, or a range. For information about specifying the key data for a complex object specifier record, see “Creating a Complex Object Specifier Record” on page 2-128.
A simple object specifier record requires less work to support than a complex object specifier record, but permits the specification of a more limited range of Apple event objects. Although complex object specifier records can be difficult to construct, they allow your application great flexibility in specifying Apple event objects.
Simple object specifier records can be used with all the Apple events in the Core suite and a few others. Applications that support complex object specifier records also support simple object specifier records. If your application supports only simple object specifier records and it receives a complex object specifier record, it should return the result code errAEeventNotHandled.
The key forms available for use in a complex object specifier record are not limited to those listed in this section. The key form formWhose, which is described in “Supporting Whose Descriptor Records” on page 2-170, is a special key form created by the Apple Event Manager that optimizes the resolution of complex object specifier records for applications that support whose descriptor records. You can also define your own key forms for use by your own application; if you think you need to do this, check with AEDA first.
For information about using object accessor functions with the AEResolve function to resolve simple object specifier records, see “Resolving Object Specifier Records,” which begins on page 2-53.
Creating a Simple Object Specifier Record
This section shows how to use the CreateObjSpecifier function to create a simple object specifier record. You can also create each descriptor record for a simple object specifier record separately, then combine them in an AE record and coerce the AE record to an object specifier record. However, in most cases it’s preferable to use the CreateObjSpecifier function, which eliminates several steps that are required if you create an AE record first.
As explained in the previous section, you can specify constants (which represent descriptor types, or four-letter codes) for the desired class and key form, and descriptor records for the container and key data, as parameters to the CreateObjSpecifier function. The CreateObjSpecifier function automatically creates the necessary keyword-specified descriptor records for the class ID, container, key form, and key data, and returns the resulting object specifier record as a descriptor record of type typeObjectSpecifier.
Listing 2-22 shows how the CreateObjSpecifier function creates an object specifier record from parameters that an application specifies.
Creating an object specifier record using CreateObjSpecifier
The code shown in Listing 2-22 demonstrates how an application might use the CreateObjSpecifier function to create four keyword-specified descriptor records as part of a descriptor record of typeObjectSpecifier. The CreateObjSpecifier function returns a result code of noErr if the object specifier record was successfully created. The object specifier record returned in the myObjSpecRec parameter describes an Apple event object of the class specified by the desiredClass parameter, located in the container specified by the myObjectContainer parameter, with the key form specified by the myKeyForm parameter and key data specified by the myKeyDataDesc parameter. You can specify TRUE in the disposeInputs parameter if you want the CreateObjSpecifier function to dispose of the descriptor records you created for the myObjectContainer and myKeyData parameters. If you specify FALSE, then your application is responsible for disposing of these leftover descriptor records.
Listing 2-23 shows an application-defined function that uses CreateObjSpecifier to create an object specifier record for the first row in the table named “Summary of Sales” in the document “Sales Report,” then uses the object specifier record returned in the myObjSpecRec parameter as the direct parameter for a Get Data event.
Using CreateObjSpecifier in an application-defined function
FUNCTION MyRequestRowFromTarget (targetAddress: AEAddressDesc;
The MyRequestRowFromTarget function shown in Listing 2-23 specifies the class ID as cRow, indicating that the desired Apple event object is a row in a table. It uses the application-defined function MyCreateTableContainer to create an object specifier record for the table that constains the row, passing “Summary of Sales, 1991” and “Sales Report” as the second and third parameters to identify the name of the table and the name of the document that contains the table. (The next section, “Specifying the Container Hierarchy,” explains how to construct the MyCreateTableContainer function). It then specifies the key form as the constant formAbsolutePosition, which indicates that the key data specifies the position of the row within its container; sets the keyData variable to 1, indicating the first row, and uses AECreateDesc to create a descriptor record for the key data; and uses CreateObjSpecifier to create the object specifier record that describes the desired word.
The desired row is now fully described by the myObjSpecRec variable, which contains a descriptor record of type typeObjectSpecifier that contains the three nesting object specifier records shown in Figure 2-23 on page 2-120. After using AECreateAppleEvent to create a Get Data event, the MyRequestRowFromTarget function uses the AEPutParamDesc function to add the myObjSpecRec variable to the Get Data event as a direct parameter, then uses AESend to send the Get Data event.
Specifying the Container Hierarchy
Since the container for an object specifier record usually consists of a chain of other object specifier records that specify the container hierarchy, your application must create all the object specifier records in the chain, starting with the record for the outermost container (see Figure 2-23 on page 2-120). Listing 2-24 and Listing 2-25 demonstrate how to use the CreateObjSpecifier function to create the first two object specifier records in such a chain: the records for a document and a table.
Specifying a document container
FUNCTION MyCreateDocContainer (VAR myDocContainer: AEDesc;
docName: Str255): OSErr;
VAR
myDocDescRec: AEDesc;
nullDescRec: AEDesc;
myErr: OSErr;
BEGIN
{create a descriptor record for the name of the document}
The function MyCreateDocContainer in Listing 2-24 creates an object specifier record that identifies a document by name. It starts by using the AECreateDesc function to create two descriptor records: one of type typeChar for the name of the document, and one of type typeNull for the null descriptor record that specifies the default container (since the document is not contained in any other Apple event object). These two descriptor records can then be used as parameters for the CreateObjSpecifier function, which returns an object specifier record (that is, a descriptor record of type typeObjectSpecifier) in the myDocContainer variable. The object specifier record specifies an Apple event object of the object class cDocument in the container specified by the nullDescRec variable with a key form of formName and the key data specified by the MyDocDescRec variable. This object specifier can be used by itself to specify a document, or it can be used to specify the container for another Apple event object.
Listing 2-25 shows an application-defined function, MyCreateTableContainer, that creates an object specifier record describing a table contained in a document. The MyCreateTableContainer function uses the MyCreateDocContainer function shown in Listing 2-24 to create the object specifier record that specifies its container.
Specifying a table container
FUNCTION MyCreateTableContainer(VAR myTableContainer: AEDesc;
{ first specify the descriptor record for the key data }
IF myErr = noErr THEN
myErr := AECreateDesc(typeChar, @tableName[1],
Length(tableName), myTableDescRec); IF myErr = noErr THEN
myErr := CreateObjSpecifier(cTable, myDocDescRec,
formName, myTableDescRec,
TRUE, myTableContainer);
MyCreateTableContainer:= myErr;
END;
The function MyCreateTableContainer in Listing 2-25 starts by using the function MyCreateDocContainer from Listing 2-24 to create an object specifier record that identifies the table’s container—the document in which the table is located. Then it uses the AECreateDesc function to create a descriptor record for the key data—a name that, when combined with the key form formName, will identify the table in the document. The object specifier record for the document and the descriptor record specifying the table’s name are passed to the function CreateObjSpecifier. It returns an object specifier record in the myTableContainer parameter that specifies an Apple event object of the object class cTable in the container specified by the MyDocDescRec variable with a key form of formName and the key data specified by the myTableDescRec variable. This object specifier record can be used by itself to specify a table, or it can be used to specify the container for another Apple event object.
Listing 2-23 uses the MyCreateTableContainer function shown in Listing 2-25 to specify the container hierarchy illustrated in Figure 2-23 on page 2-120.
Creating a Complex Object Specifier Record
If you want your application to specify relative positions, tests, and ranges that identify groups of related Apple event objects for a server application, your application must include routines that create complex object specifier records. Complex object specifier records can specify at least four key forms that are not available to simple object specifier records: formRelativePosition, formTest, formRange, and formWhose. These additional key forms provide considerably more flexibility than the key forms available for simple object specifier records. You can also define key forms of your own, if necessary, for use in complex object specifier records.
Like a simple object specifier record, a complex object specifier record consists of four keyword-specified descriptor records. You can create the first descriptor record, for the object class ID, the same way you would for a simple object specifier record. When you create the other three keyword-specified descriptor records, however, you can use several additional Apple Event Manager routines and descriptor types to specify any combination of Apple event objects.
Both simple and complex object specifier records almost always include nested object specifier records that specify the container hierarchy for the requested Apple event object. In a simple object specifier record, the relationship between an Apple event object and its container is always simple containment: it is located inside its container. You can use one of two descriptor types to describe the container for a simple object specifier record: typeObjectSpecifier, for other object specifier records, or typeNull, for the default descriptor record that indicates the top of the container hierarchy.
In a complex object specifier record, the specified container may not actually contain the requested Apple event object. Instead, the relationship between the container and the element it contains can be defined differently, depending on the key form. In addition to the simple containment relationship that a simple object specifier record can describe, the key forms available to a complex object specifier record can describe the following kinds of relationships between a container and the elements it contains:
Key form Relationship of container to its elements
formRelativePosition The container is a single Apple event object or a group of Apple event objects that contains one or more elements; the elements are located immediately before or immediately after the container. For example, you can specify the table named “Summary of Sales, 1991” as the container for whatever follows it.
formTest or formWhose The container is a single Apple event object or a group of Apple event objects that contains one or more elements that pass a test specified by the key data. For example, you can specify a document named “Sales Report” as the container for all the tables in that document that begin with the word “Sales.”
formRange The container consists of an Apple event object that contains a range of elements between two other elements in the same container. For example, you can specify the document “Sales Report” as the container for the range of paragraphs between a table named “Summary of Sales, 1991” and a table named “Summary of Sales, 1992.”
In addition to these relationships, new key forms—either new standard key forms or custom key forms defined for a particular class of objects—can specify other relationships between specified Apple event objects and their container.
Object specifier records that specify the key forms formTest or formRange require key data that consists of several interconnected descriptor records, including object specifier records that identify either a group of elements to be tested or the boundary elements that demarcate a range. Object specifier records provided as part of the key data can specify their containers using two special descriptor types: typeObjectBeingExamined, which specifies a container that changes as a group of elements are tested one at a time, and typeCurrentContainer, which specifies the container for a boundary element in a range. Boundary elements of a range are always located in the same container as the range itself. Both of these descriptor types require NIL as their data, since they act much like variables whose value is supplied by the Apple Event Manager according to other information provided in the container hierarchy. The descriptor types typeObjectBeingExamined and typeCurrentContainer can be used only for object specifier records that are part of key data.
Complex object specifier records can therefore make use of a total of four descriptor types to specify containers:
Descriptor type Corresponding data
typeObjectSpecifier Any other object specifier record.
typeNull NIL. Specifies the default container that indicates the
top of the container hierarchy.
typeObjectBeingExamined NIL. Specifies the container for an object specifier record that changes as a group of elements are tested one at a time. This descriptor type acts much like a variable whose value matches the element currently being tested. It is used only for object specifier records that are part of the key data corresponding to a key form of formtest.
typeCurrentContainer NIL. Specifies a container for an element that demarcates one boundary in a range. The container for a boundary element is always the same as the container for the entire range. This descriptor type is used only for object specifier records that are part of the key data corresponding to a key form of formRange.
You can specify the formPropertyID, formName, and formAbsolutePosition key forms for a complex object specifier record the same way you specify them for a simple object specifier record. However, in addition to providing data of descriptor type typeLongInteger for the key data that corresponds to a key form of formAbsolutePosition, you can provide data of descriptor type typeAbsoluteOrdinal that consists of one of these constants:
Constant Meaning
kAEFirst The first element in the specified container.
kAEMiddle The element in the middle of the specified container.
kAELast The last element in the specified container.
kAEAny A single element chosen at random from the specified
container.
kAEAll All the elements in the specified container.
The other key forms that you can use in a complex object specifier record require your application to specify the key data using several descriptor types that are not available for simple object specifier records. The remainder of this section describes how to use the key forms formRelativePosition, formTest, and formRange, and provides sample code that illustrates how to create an object specifier record using the key form formTest. For information about the key form formWhose, see “Supporting Whose Descriptor Records” on page 2-170.
Specifying a Relative Position
The key form formRelativePosition allows you to specify key data identifying an element or a set of elements that are immediately before or after the specified container. For example, if the container is a table, you could use a key form of formRelativePosition to specify the paragraph before or after the table. To specify the key data for a key form of formRelativePosition, your application must create a descriptor record of typeEnumeration that specifies one of these constants:
Constant Description
kAENext Specifies the Apple event object after the specified container.
kAEPrevious Specifies the Apple event object before the specified container.
You can use AECreateDesc to create a descriptor record that specifies one of these constants, then use CreateObjectSpecifier to add it to an object specifier record as a keyword-specified descriptor record.
Specifying a Test
The key form formTest allows you to specify key data that identifies one or more elements in the specified container that pass a test. To specify the key data for a key form of formTest, your application must construct several interconnected descriptor records that specify logical expressions and, if necessary, comparisons. For example, to specify “the first row in which the First Name column equals ‘John’ and the Last Name column equals ‘Chapman’ in the table MyAddresses of the database GigaBase,” your application must construct a logical expression that applies the logical operator AND to two separate comparisons for each row: a comparison of the “First Name” column to the word “John” and a comparison of the “Last Name” column to the word “Chapman.” The listings in the remainder of this section demonstrate how to create a complex object specifier record for this example.
Since both the database and the table in this example are specified by name, it would be convenient to have an application-defined routine that creates an object specifier record that uses the key form formName. The MyCreateFormNameObjSpecifier function shown in Listing 2-26 can be used for this purpose.
Creating an object specifier record with the key form formName
FUNCTION MyCreateFormNameObjSpecifier(class: DescType;
The MyCreateFormNameObjSpecRec function shown in Listing 2-26 returns an object specifier record in the resultObjSpecRec parameter that describes an Apple event object of the class specified by the class parameter, located in the container specified by the container parameter, with the key form formName and key data specified by the keyDataName parameter. This function is used in Listing 2-29 on page 2-140 to create object specifier records that use the key form formName for the database and the table.
The next object specifier that needs to be created specifies “the rows in which the First Name column equals ‘John’ and the Last Name column equals ‘Chapman’.” To identify the rows that pass this test, the Apple Event Manager needs to evaluate a two comparisons (the comparison of each row of the First Name column to the word “John,” and the comparison of each row of and the Last Name column to the word “Chapman”).
The Apple Event Manager evaluates comparisons and logical expressions on the basis of information in comparison descriptor records and logical descriptor records. A comparison descriptor record is a descriptor record of type typeCompDescriptor that the Apple Event Manager uses to compare the specified elements in a container, one at a time, either to another Apple event object or to the data in a descriptor record. A comparison descriptor record is a coerced AE record that consists of three keyword-specified descriptor records with the following keywords:
Keyword Description
keyAECompOperator A descriptor record of type typeType that specifies one of several possible comparison operators.
keyAEObject1 An object specifier record that identifies the element that is currently being compared to the Apple event object or data specified by the descriptor record identified by the keyword keyAEObject2.
keyAEObject2 Either an object specifier record or another descriptor record.
You can specify one of these constants for the data in a descriptor record specified by the keyword keyAECompOperator:
Constant Comparison operator
kAEGreaterThan >
kAEGreaterThanEquals ≥
kAEEquals =
kAELessThan <
kAELessThanEquals ≤
kAEBeginsWith Begins with
kAEEndsWith Ends with
kAEContains Contains
Your application is not required to support all the comparison operators that are available. Not all comparison operators make sense for all objects; for example, the “begins with” operator probably doesn’t make sense for Apple event objects of type cRectangle. It is up to you to decide which comparison operators are appropriate for your application to support, and how to interpret them. If necessary, you can define your own custom comparison operators; if you think you need to do this, check with AEDA first.
You can use the CreateCompDescriptor function to create a comparison descriptor record, or you can create an AE record and use AECoerceDesc to coerce it to a comparison descriptor record. Listing 2-27 shows an example of an application-defined routine that creates an object specifier record and a descriptor record of typeChar, then uses the CreateCompDescriptor function to add them to a comparison descriptor record.
Creating a comparison descriptor record
FUNCTION MyCreateComparisonDescRec (VAR compDesc: AEDesc;
The MyCreateComparisonDescRec function takes two strings and uses them to create a comparison descriptor record. The string passed in the second parameter specifies the name of the column whose contents should be compared to the string passed in the third parameter. First, the MyCreateComparisonDescRec function uses AECreateDesc to create a descriptor record of typeObjectBeingExamined, which is returned in the variable myObjectExaminedContainer. The code that follows uses AECreateDesc to create a descriptor record of descriptor type typeChar, whose data consists of the string in the variable colName, and which is returned in the variable colNameDesc. The code then passes the variables myObjectExaminedContainer and colNameDesc to the CreateObjSpecifier function, which uses them to create an object specifier record, returned in the logicalContainer variable, that will become the keyword-specified descriptor record with the keyword keyAEObject1.
Next, the MyCreateComparisonDescRec function uses AECreateDesc and the name parameter to create the descriptor record for keyAEObject2, which AECreateDesc returns in the nameDesc variable. Finally, the code passes the constant kAEEquals, the variable logicalContainer, and the variable nameDesc to the CreateCompDescriptor function, which creates a comparison descriptor record that allows the Apple Event Manager (with the help of object comparison functions provided by your application) to determine whether the specified column in the row currently being checked equals the specified string.
Comparison records often form part of a logical descriptor record, which is a descriptor record of type typeLogicalDescriptor that specifies a logical expression—that is, an expression that the Apple Event Manager evaluates to either TRUE or FALSE. The logical expression is constructed from a logical operator (one of the Boolean operators AND, OR, or NOT) and a list of logical terms to which the operator is applied. Each logical term in the list can be either another logical descriptor record or a comparison descriptor record. If the logical operator is AND or OR, the list can contain any number of logical terms, and the logical operator is applied to all the terms in the list. For example, the logical descriptor data shown in Figure 2-25 on page 2-138 consists of the logical operator AND and a list of logical terms that contains two comparison descriptor records. The entire logical descriptor record corresponds to the logical expression “the First Name column equals ‘John’ AND the Last Name column equals ‘Chapman’.” If the logical operator is NOT, the list must contain a single term.
A logical descriptor record is a coerced AE record that consists of two descriptor records specified by the following keywords:
Keyword Description
keyAELogicalOperator A descriptor record of typeEnumeration that identifies the logical operator to be applied to the logical terms.
keyAELogicalTerms A descriptor record of typeAEList that lists the descriptor records to which the logical operator is to be applied. The list can include logical descriptor records, comparison descriptor records, or both. keyAELogicalOperator
You can specify one of these constants for the data in a descriptor record specified by the keyword keyAELogicalOperator:
Constant Logical operator
kAEAND AND
kAEOR OR
kAENOT NOT
You can use the CreateLogicalDescriptor function to create a logical descriptor record, or you can create an AE record and use the AECoerceDesc function to coerce it to a comparison descriptor record. Listing 2-28 provides shows an application-defined function that adds two comparison descriptor records to a descriptor list, then uses the CreateLogicalDescriptor function to create a logical descriptor record whose logical terms consists of the two comparison descriptor records.
Creating a logical descriptor record
FUNCTION MyCreateLogicalDescRec(compDesc1, compDesc2: AEDesc;
logicalOperator: DescType;
VAR logicalDesc: AEDesc): OSErr;
VAR
logicalTermsList: AEDescList;
myErr: OSErr;
BEGIN
{create a logical descriptor record that contains two }
The key data for the keyTest key form always consists of a logical descriptor record whose logical terms include whatever combination of logical descriptor records and/or comparison descriptor records is appropriate for the tests your application might need to apply to the elements in a container. Figure 2-24 shows four object specifier records that specify the container hierarchy for the first row in the table “MyAddresses” of the database “GigaBase” that meets a test. The object specifier record on the left in Figure 2-24 specifies the first row contained in the set of rows that form its container. The container for the first row is specified by an object specifier record for a set of rows that meet a test. The two object specifier records on the right in Figure 2-24 specify the table named “MyAddresses,” which contains the rows to be tested, in the database named “GigaBase.”
The container hierachy for the first row in a document that meets a test
A logical descriptor record that specifies a test
The key form for the second object specifier record in Figure 2-24, which specifies a set of lines that meet a test, is formTest. The corresponding key data consists of the logical descriptor record illustrated in Figure 2-25, which applies the logical operator AND to two logical terms: a comparison descriptor record that specifies all the rows in the container (that is, in the table “MyAddresses”) in which the column named “First Name” equals “John,” and another comparison descriptor record that specifies all the rows in which the column named “First Name” equals “Chapman.” Only the rows in the table “MyAddresses” for which both comparison descriptor records evaluate as TRUE pass the test.
Note that the keyword-specified descriptor record with the key word keyAEObject1 in each comparison record shown in Figure 2-25 consists of an object specifier record. The container for each of these object specifier records is specified by a descriptor record of typeObjectBeingExamined, which functions much like a variable that changes as the Apple Event Manager tests successive rows in the table. The Apple event object specified by each of these object specifier records consists of a column in the row, which the Apple Event Manager (with the help of your object comparison function) compares to the string in the keyword-specified descriptor record with the keyword keyAEObject2 using the comparison operator in the keyword-specified descriptor record with the keyword keyAECompOperator.
Listing 2-29 uses the application-defined functions shown in Listing 2-26, Listing 2-27, and Listing 2-28 to build the complex object specifier record illustrated in Figure 2-24 and Figure 2-25.
Creating a complex object specifier record
FUNCTION MyCreateCompleteObjSpecRec (VAR theResultObj: AEDesc): OSErr;
The MyCreateCompleteObjSpecRec function shown in Listing 2-29 begins by using AECreateDesc to create a null descriptor record, then uses the MyCreateFormNameObjSpecifier function (shown in Listing 2-26) to specify the default container for the database named “GigaBase.” The code then calls the MyCreateFormNameObjSpecifier function again, this time passing the object specifier record for “GigaBase” to specify the container for the table “MyAddresses.” The next two calls are both to the MyCreateComparisonDescRec function (shown in Listing 2-27), which creates the comparison descriptor records that allow the Apple Event Manager to compare the First Name column and Last Name column to the names “John” and “Chapman,” respectively. The next call passes these two comparison descriptor records to the MyCreateLogicalDescRec function (shown in Listing 2-28) in the compDesc1 and compDesc2 variables. Now all the components of the logical descriptor record are ready to assemble. The next call, to CreateObjSpecifier, specifies the logical descriptor record in the logicalTestDesc variable as the key data for the object specifier record that specifies the test. A call to the Apple Event Manager routine CreateOffsetDescriptor then creates an offset descriptor record that contains the integer 1. Finally, the code passes the offset descriptor record to the CreateObjSpecifier function in the rowOffset variable to create the final object specifier record, which describes the requested row as the first row that passes the test.
The CreateOffsetDescriptor function creates a descriptor record of type typeLongInteger that can be used as the key data with a key form of formAbsolutePosition to indicate an element’s offset within its container. A positive integer indicates an offset from the beginning of the container (the first element has an offset of 1), and a negative integer indiates an offset from the end of the container (the last element has an offset of -1). Using CreateOffsetDescriptor accomplishes the same thing as setting a variable to an integer and passing the variable to AECreateDesc to create a descriptor record of type typeLongInteger.
Specifying a Range
The key form formRange allows you to specify key data that identifies a range of elements in the specified container. To specify the key data for a key form of formRange, your application must create a range data descriptor record, which is a descriptor record of type typeRangDescriptor that the Apple Event Manager uses to identify the two Apple event objects that specify the beginning and end of a range of elements. A range data descriptor record is a coerced AE record that consists of two keyword-specified descriptor records with the following keywords:
Keyword Description
keyAERangeStart An object specifier record that identifies the first Apple event object in the desired range.
keyAERangeStop An object specifier record that identifies the last Apple event object in the desired range.
The elements that specify the beginning and end of the range, which are known as boundary objects, do not have to belong to the same object class as the elements in the range itself. For example, an object specifier record for a range of text in a document could specify the table named “Summary of Sales, 1991” as the first boundary object and the figure named “Best Selling Widget for 1991” as the second boundary object for a range that consists of all the text between the table and the figure. Any word processor that keeps track of the relative positions of text, tables, and figures would be capable of supporting such a request.
You can use the CreateRangeDescriptor function to create a range data descriptor record, or you can create an AE record and use AECoerceDesc to coerce it to a range data descriptor record. Listing 2-30 provides an example of an application-defined routine that creates two object specifier records, then uses the CreateRangeDescriptor function to add them to a range data descriptor record.
Creating a range descriptor record
FUNCTION MyCreateRangeDescriptor (rangeDescRec: AEDesc): OSErr;
VAR
rangeStart: AEDesc;
rangeEnd: AEDesc;
docContainer: AEDesc;
tableNameDescRec : AEDesc;
figureNameDescRec : AEDesc;
myErr: OSErr;
BEGIN
{create the object specifier record for the start of the range }
{ (the table named 'Summary of Sales' in 'MyDoc' document)}
After using two application-defined routines to create an object specifier record for a document and a descriptor record for a table’s name, Listing 2-30 uses the CreateObjSpecifier function to create an object specifier record that identifies the beginning of the range. The parameters to CreateObjSpecifier specify that the beginning of the range is an Apple event object of the object class cTable in the container specified by the docContainer variable, with a key form of formName and key data that identifies the table by name. A second call to CreateObjSpecifier creates the object specifier record that identifies the end of the range—an Apple event object of the cFigure object class in the container specified by the docContainer variable, with a key form of formName and key data that identifies the figure by name.
Finally, the code in Listing 2-30 uses the CreateRangeDescriptor function to create the range descriptor record, specifying the two previously created object specifier records as the beginning and end of the range.
Sending an Apple Event
To send an Apple event, you first create an Apple event, add parameters and attributes to the Apple event, and then use the AESend function to send it.
When you send an Apple event, you specify various options to indicate how the server should handle the Apple event. You request a user interaction level from the server and specify whether the server can directly switch to the foreground if user interaction is needed, whether your application is willing to wait for a reply Apple event, whether reconnection is allowed, and whether your application wants a return receipt for the Apple event.
You specify these options by setting flags in the sendMode parameter for AESend. Here are the constants that represent these flags:
If your application wants a reply Apple event, specify the kAEQueueReply or kAEWaitReply flag. If your application wants to receive the reply Apple event in its event queue, use kAEQueueReply. If your application wants to receive the reply Apple event in the reply parameter for AESend and is willing to give up the processor while waiting for the reply, use kAEWaitReply. If your application does not want a reply Apple event and does not need to wait for the server to handle the Apple event, specify kNoReply.
If your application specifies kAENoReply or kAEQueueReply, the AESend function returns immediately after using the Event Manager to send the event. In this case, a noErr result code from AESend indicates that the Apple event was successfully sent by the Event Manager; it does not mean that the server accepted or handled the Apple event.
When AESend returns, the reply parameter does not contain valid data if your application specifies kAENoReply or kAEQueueReply. The kAENoReply flag indicates that the Apple Event Manager will not return the reply Apple event to your application. The kAEQueueReply flag indicates that your application wants to receive the reply via its event queue rather than the reply parameter of AESend.
If your application specifies kAEWaitReply, the Apple Event Manager uses the Event Manager to send the event. The Apple Event Manager then calls the WaitNextEvent function on behalf of your application, causing your application to yield the processor. This gives the server application a chance to receive and handle the Apple event. Your application continues to yield the processor until the server handles the Apple event or the request times out.
You use one of the three flags—kAENeverInteract, kAECanInteract, and kAEAlwaysInteract—to specify whether the server should interact with the user when handling the Apple event. Specify kAENeverInteract if the server should not interact with the user when handling the Apple event. You might specify this constant if you don’t want the user to be interrupted while the server is handling the Apple event.
Use the kAECanInteract flag if the server should interact with the user when the user needs to supply information to the server. Use the kAEAlwaysInteract flag if the server should interact with the user whenever the server normally asks a user to confirm a decision or interact in any other way, even if no additional information is needed from the user. Note that it is the responsibility of the server and client applications to agree on how to interpret the kAEAlwaysInteract flag.
If the client application does not set any one of the user interaction flags, the Apple Event Manager sets a default, depending on the location of the target of the Apple event. If the server application is on a remote computer, the Apple Event Manager sets the kAENeverInteract flag as the default. If the target of the Apple event is on the local machine, the Apple Event Manager sets the kAECanInteract flag as the default.
The server application should call AEInteractWithUser if it needs to interact with the user. If both the client and the server allow user interaction, the Apple Event Manager attempts to bring the server to the foreground if it is not already the foreground process. If both the kAECanSwitchLayer and the kAEWaitReply flags are set, and if the client application is the active application on the local machine, the Apple Event Manager brings the server application directly to the front. Otherwise, the Apple Event Manager posts a notification request to ask the user to bring the server application to the front, regardless of whether the kAECanSwitchLayer flag is set. This ensures that the user will not be interrupted by an unexpected application switch.
You should specify the kAECanSwitchLayer flag only when the client and server applications reside on the same computer. In general, you should not set this flag if it would be confusing or inconvenient to the user for the server application to come to the front unexpectedly.
Specify the kAEDontReconnect flag if the Apple Event Manager should not reconnect if it receives a session closed error from the PPC Toolbox. If you don’t set this flag, the Apple Event Manager automatically attempts to reconnect and reestablish the session.
Specify the kAEWantReceipt flag if your application wants notification that the server application has accepted the Apple event. If you specify this flag and the server application does not accept the Apple event within the time specified by the timeOutInTicks parameter to AESend, the AESend function will return a timeout error.
Listing 2-31 illustrates how to send a Multiply event (an imaginary Apple event for multiplying two long integers). It first creates an Apple event, adds parameters containing the numbers to multiply, then sends it, specifying various options. It also illustrates how to handle the reply Apple event that contains the result.
If you want to send Apple events, your application must set flags in its \qSIZE\q resource that indicate that it can handle high-level events, and must provide handlers for the required Apple events. See “Accepting an Apple Event” on page 2-60 for information on setting the appropriate flags in the \qSIZE\q resource, and “Handling the Required Apple Events” on page 2-72 for information supporting the required Apple events.<36pt\>\x12 <8bat\>u
Sending an Apple event
FUNCTION MySendMultiplyEvent (serverAddress: AEAddressDesc;
firstOperand: LongInt;
secondOperand: LongInt;
VAR replyResultLongInt: LongInt):
OSErr;
CONST
kArithmeticClass = 'ARTH'; {event class for arithmetic }
{ Apple events}
kMultiplyEventID = 'MULT'; {event ID for Multiply event}
keyMultOperand1 = 'OPN1'; {keyword for first parameter}
keyMultOperand2 = 'OPN2'; {keyword for second parameter}
{the Apple event wasn't successfully dispatched, }
{ the request timed out, the user canceled, or other error}
END;
MySendMultiplyEvent := myErr;
END;
The code in Listing 2-31 first creates an Apple event with kArithmeticClass as the event class and kMultiplyEventID as the event ID. It also specifies the server of the Apple event. See “Specifying a Target Address” on page 2-116 for information on specifying a target address, and see “Creating an Apple Event” on page 2-110 for more information on how to create an Apple event.
The Multiply event shown in Listing 2-31 contains two parameters, each of which specifies a number to multiply. See “Adding Parameters to an Apple Event” on page 2-111 for examples of how to specify the parameters for the AEPutParamPtr function.
After adding the parameters to the event, the code uses AESend to send the event. The first parameter to AESend specifies the Apple event to send—in this example, the Multiply event. The next parameter specifies the reply Apple event.
This example specifies kAEWaitReply in the third parameter, indicating that the client is willing to yield the processor for the specified timeout value (120 ticks, or 2 seconds). The kAENeverInteract flag indicates that the server should not interact with the user when processing the Apple event. The Multiply event is sent using normal priority, meaning it is placed at the end of the event queue. You can specify the kAEHighPriority flag to place the event in the front of the event queue, but this is not recommended.
The next to last parameter specifies the address of an idle function. If you specify kAEWaitReply, you should provide an idle function. This function should process any update events, null events, operating-system events, or activate events that occur while your application is waiting for a reply. See “Writing an Idle Function” on page 2-150 for sample code that shows an idle function.
The last parameter to AESend specifies a filter function. You can supply a filter function to filter high-level events that your application may receive while waiting for a reply Apple event. You can specify NIL for this parameter if you do not need to filter high-level events while waiting for a reply. See “Writing a Reply Filter Function” on page 2-152 for more information.
If your application specified kAEWaitReply and AESend returns a noErr result code, the result code indicates that the Apple event was sent succesfully, not that the server has completed the requested action successfully. Therefore, you should find out whether a result code was returned from the handler by checking the reply Apple event for the existence of the parameter whose keyword is keyErrorNumber. If the keyErrorNumber parameter does not exist or contains the noErr result code, you can use AEGetParamPtr to get the parameter you’re interested in from the reply Apple event.
The code in Listing 2-31 checks the function result of AESend. If AESend returns noErr, the code then checks the keyErrorNumber parameter of the reply Apple event to determine whether the server successfully handled the Apple event. If this parameter exists and indicates that an error occurred, then the code gets the error string out of the keyErrorString parameter. Otherwise, the server performed the request, and the reply Apple event contains the answer to the multiplication request.
When you have finished using the Apple event specified in the AESend function and finished with the reply Apple event, you must dispose of their descriptor records using the AEDisposeDesc function.
If your application sends Apple events to itself using a typeProcessSerialNumber address descriptor record with the value kCurrentProcess, the Apple Event Manager jumps directly to the appropriate Apple event handler without going through the normal event-processing sequence. As a result, your application will not run appreciably more slowly when it sends Apple events to itself. Because the Apple Event Manager calls your application’s Apple event handlers directly, without going through the PPC Toolbox, Apple events your application sends to itself do not appear in your application’s high-level event queue.<36pt\>\x12 <8bat\>s
Dealing With Timeouts
When your application calls AESend and chooses to wait for the server application to handle the Apple event, it can also specify the maximum amount of time that it is willing to wait for a response. You can specify a timeout value in the timeOutInTicks parameter to AESend. You can either specify a particular length of time, in ticks, that your application is willing to wait, or you can specify the kNoTimeOut constant or the kAEDefaultTimeout constant.
Use the kNoTimeOut constant to indicate that your application is willing to wait forever for a response from the server. You should use this value only if you are sure that the server will respond in a reasonable amount of time. You should also implement a method of checking if the user wants to cancel. The idle function that you specify as a parameter to AESend should check the event queue for any instances of Command-period and immediately return TRUE as its function result if it finds a request to cancel in the event queue.
Use the kAEDefaultTimeout constant if you want the Apple Event Manager to use a default value for the timeout value. The Apple Event Manager uses a timeout value of about one minute if you specify this constant.
Note that if you set the kAEWaitReply flag and the server doesn’t have a handler for the Apple event, the server immediately returns the errAEEventNotHandled result code.
If the server doesn’t respond within the length of time specified by the timeout value, AESend returns the errAETimeout result code and a reply Apple event that does not contain any data. This result code does not necessarily mean that the server failed to perform the requested action; it only means that the server did not complete processing within the specified time. The server might still be processing the Apple event, and it might still send a reply.
If the server finishes processing the Apple event sometime after the time specified in the timeout parameter has expired, it returns a reply Apple event to AEProcessAppleEvent. The Apple Event Manager then adds the actual data to the reply.
This means your application can continue to check the reply Apple event to see if the server has responded, even after the time expires. If the server has not yet sent the reply when the client attempts to extract data from the reply Apple event, the Apple Event Manager functions return the errAEReplyNotArrived result code. After the reply Apple event returns from the server, the client can extract the data in the reply.
Additionally, the server can determine the timeout value specified by the client by examining the keyTimeoutAttr attribute in the Apple event. You can use the value of this attribute as a rough estimate of how much time your handler has to respond. You can assume that your handler has less time to respond than the timeout value, because transmitting the Apple event uses some of the available time, as does transmitting the reply Apple event back to the client, and the event may have been in the queue for a while already.
If your handler needs more time than is specified in the keyTimeoutAttr attribute, you can reset the timer by using the AEResetTimer function. This function resets the timeout value of an Apple event to its starting value.
Writing an Idle Function
This section describes how to write an idle function when using the AESend or AEInteractWithUser function.
When your application sends an Apple event, you can wait for the server application to receive and finish handling the Apple event, or you can continue processing. If your application chooses to continue processing, the AESend function returns immediately after using the Event Manager to send the event. If your application chooses to wait for the server to handle the event, the AESend function does not return until either the server application finishes handling the Apple event or a specified amount of time expires.
Your application specifies its preferences by setting flags in the sendMode parameter to AESend. Your application can specify kAENoReply if it does not want to receive a reply, kAEQueueReply if it wants to receive the reply in its event queue, or kAEWaitReply if it wants the reply returned in the reply parameter of AESend and is willing to give up the processor while waiting for the reply.
If your application specifies the kAEWaitReply flag, the AESend function calls WaitNextEvent on behalf of your application. This yields the processor to other processes, so that the server has an opportunity to receive and process the Apple event sent by your application. While your application is waiting for a reply, it cannot receive events unless it provides an idle function.
If your application provides a pointer to an idle function as a parameter to the AESend function, AESend calls your idle function whenever an update event, null event, operating-system event, or activate event is received for your application. Your application can process high-level events that it receives while waiting for a reply by providing a reply filter function. See the next section, “Writing a Reply Filter Function,” for more information.
In a similar manner, when your application calls the AEInteractWithUser function, your application can also yield the processor. If AEInteractWithUser needs to post a notification request to bring your application to the front, your application yields the processor until the user brings your application to the front. To receive events while waiting for the user to bring your application to the front, you must provide an idle function.
If your application provides a pointer to an idle function as a parameter to the AEInteractWithUser function, AEInteractWithUser calls your idle function whenever an update event, null event, operating-system event, or activate event is received for your application.
An idle function must use this syntax:
FUNCTION MyIdleFunction (VAR theEventRecord: EventRecord;
VAR sleepTime: LongInt;
VAR mouseRgn: RgnHandle): Boolean;
The parameter theEventRecord is the event record of the event to process. The sleepTime parameter and mouseRgn parameter are values that your idle function sets the first time it is called; thereafter they contain the values your function set. Your idle function should return a Boolean value that indicates whether your application wishes to continue waiting. Set the function result to TRUE if your application is no longer willing to wait for a reply from the server or for the user to bring the application to the front. Set the function result to FALSE if your application is still willing to wait.
The first time your idle function is called, you may set the values for the sleepTime and mouseRgn parameters. These parameters are used in the same way as the sleep and mouseRgn parameters of the WaitNextEvent function. Specify in the sleepTime parameter the amount of time (in ticks) during which your application agrees to relinquish the processor if no events are pending for it.
In the mouseRgn parameter, you specify a screen region that determines the conditions in which your application is to receive notice of mouse-moved events. Your idle function receives mouse-moved events only if your application is the front application and the mouse strays outside the region you specify.
Your idle function receives only update events, null events, operating-system events, and activate events. When your idle function receives a null event, it can use the idle time to update a status dialog box, animate cursors, or perform similar tasks. If your idle function receives any of the other events, it should handle the event as it normally would if received in its event loop.
Listing 2-32 shows an example of an idle function that can be used as an idle function for AESend or AEInteractWithUser. The idle function processes update events, null events, operating-system events, and activate events. The first time the function is called it receives a null event. At this time, it sets the sleepTime and mouseRgn parameters. The function continues to process events until the server finishes handling the Apple event or the user brings the application to the front.
Your application should implement a method of checking to see if the user wants to cancel. The MyCancelInQueue function in Listing 2-32 checks the event queue for any instances of Command-period and immediately returns TRUE as its function result if it finds a request to cancel in the event queue.
An idle function
FUNCTION MyIdleFunction (VAR event: EventRecord;
VAR sleeptime: LongInt;
VAR mouseRgn: RgnHandle): Boolean;
VAR
hiByte: Char;
myErr: OSErr;
BEGIN
MyIdleFunction := FALSE;
{the MyCancelInQueue function checks for Command-period}
IF MyCancelInQueue THEN
BEGIN
MyIdleFunction := TRUE;
Exit(MyIdleFunction);
END;
CASE event.what OF
updateEvt,
activateEvt, {every idle function should handle }
kOSEvent: { these kinds of events}
BEGIN
AdjustCursor(event.where, gCursorRgn);
DoEvent(event);
END;
nullEvent:
BEGIN
{set the sleepTime and mouseRgn parameters}
mouseRgn := gCursorRgn;
sleeptime := 10; {use the correct value for your }
{ app}
DoIdle; {the application's idle handling}
END
END; {CASE}
END;
Writing a Reply Filter Function
If your application calls AESend and chooses to yield the processor to other processes while waiting for a reply, you can provide an idle function to process update, null, operating-system, and activate events, and you can provide a reply filter function to process high-level events. The previous section describes how an idle function processes events.
Your reply filter function can process any high-level events that it is willing to handle while waiting for a reply Apple event. For example, your application can choose to handle Apple events from other processes while waiting. Note, however, that your application must maintain any necessary state information. Your reply filter function must not accept any Apple events that can change the state of your application and make it impossible to return to its previous state.
A reply filter function must use this syntax:
FUNCTION MyWaitReplyFilter (VAR theEventRecord: EventRecord;
returnID: LongInt;
transactionID: LongInt;
sender: AEAddressDesc): Boolean;
The parameter theEventRecord is the event record for a high-level event. The next three parameters contain valid information only if the event is an Apple event. The returnID parameter is the return ID for the Apple event. The transactionID parameter is the transaction ID for the Apple event. The sender parameter contains the address of the application or process that sent the Apple event.
Your reply filter function should return TRUE as the function result if you want to accept the Apple event; otherwise it should return FALSE. If your filter function returns TRUE, the Apple Event Manager calls the AEProcessAppleEvent function on behalf of your application, and your handler routine is called to process the Apple event. In this case, make sure your handler does not get called while it is still being used by an earlier call.
Writing and Installing Coercion Handlers
When your application extracts data from a parameter, it can request that the Apple Event Manager return the data using a descriptor type that is different from the original descriptor type. For example, when extracting data from the direct parameter of the Open Documents event, you can request that the alias records be returned as file system specification records. The Apple Event Manager can automatically coerce many different types of data from one to another. Table 2-1 on page 2-156 shows descriptor types and the kinds of coercion that the Apple Event Manager can perform.
You can also provide your own routines, referred to as coercion handlers, to coerce data into any other descriptor type. To install your own coercion handlers, use the AEInstallCoercionHandler function. You specify as parameters to this function
n the descriptor type of the data coerced by the handler
n the descriptor type of the resulting data
n the address of the coercion handler for this descriptor type
n a reference constant
n a Boolean value that indicates whether your coercion handler expects the data to be specified as a descriptor record or as a pointer to the actual data
n a Boolean value that indicates whether your coercion handler should be added to your application’s coercion table or the system coercion table
The system coercion table is a table in the system heap that contains handlers that are available to all applications and processes running on the same computer. The handlers in your application’s coercion table are available only to your application. When the Apple Event Manager is attempting to coerce data, it first looks for a coercion handler in your application’s coercion table. If it cannot find a handler for the descriptor type, it looks in the system coercion table for a handler. If it doesn’t find a handler there either, it returns the errAEHandlerNotFound result code.
If you add a handler to the system coercion table, the handler that you specify should reside in the system heap. If there was already an entry in the system coercion table for the same descriptor type, it is replaced. Therefore, if there is an entry in the system coercion table for the same descriptor type, you should chain it to your system coercion handler as explained in “Creating and Managing the Coercion Handler Dispatch Tables” on page 2-247.
When an application calls a system coercion handler, the A5 register is set up for the calling application. For this reason, if you provide a system coercion handler, it should never use A5 global variables or anything that depends on a particular context; otherwise, the application that calls the system coercion handler may crash.<36pt\>\x12 <8bat\>u
You can provide a coercion handler that expects to receive the data in a descriptor record or a buffer referred to by a pointer. When you install your coercion handler, you specify how your handler wishes to receive the data. It’s more efficient for the Apple Event Manager to provide your coercion handler with a pointer to the data so, whenever possible, you should write your coercion handler so that it can accept a pointer to the data.
A coercion handler that accepts a pointer to data must be a function with the following syntax:
FUNCTION MyCoercePtr (typeCode: DescType; dataPtr: Ptr;
dataSize: Size; toType: DescType;
handlerRefcon: LongInt;
VAR result: AEDesc): OSErr;
The typeCode parameter is the descriptor type of the original data. The dataPtr parameter is a pointer to the data to coerce; the dataSize parameter is the length, in bytes, of the data. The toType parameter is the desired descriptor type of the resulting data. The handlerRefcon parameter is a reference constant that is stored in the coercion table entry for the handler and passed to the handler by the Apple Event Manager whenever the handler is called. The result parameter is the resulting descriptor record returned by your coercion handler.
Your coercion handler should coerce the data to the desired descriptor type and return the resulting data in the descriptor record specified by the result parameter. Your handler should return the noErr result code if your handler successfully performs the coercion, and a nonzero result code otherwise.
A coercion handler that accepts a descriptor record must be a function with the following syntax:
FUNCTION MyCoerceDesc (theAEDesc: AEDesc; toType: DescType;
handlerRefcon: LongInt;
VAR result: AEDesc): OSErr;
The parameter theAEDesc is the descriptor record that contains the data to be coerced. The toType parameter is the descriptor type of the resulting data. The handlerRefcon parameter is a reference constant that is stored in the coercion table entry for the handler and passed to the handler by the Apple Event Manager whenever the handler is called. The result parameter is the resulting descriptor record.
Your coercion handler should coerce the data in the descriptor record to the desired descriptor type and return the resulting data in the descriptor record specified by the result parameter. Your handler should return an appropriate result code.
Table 2-1 lists the descriptor types for which the Apple Event Manager provides coercion. The first column shows the descriptor type of the data to be coerced, and the second column shows the descriptor types that the Apple Event Manager can coerce it to.
For many Apple Event Manager functions, the Apple Event Manager attempts to coerce data to the descriptor type you specify even if the result is no longer meaningful. To ensure that no coercion is performed and that the descriptor type of the result is of the same descriptor type as the original, specify typeWildCard for the desired type.<36pt\>\x12 <8bat\>u
Coercion handling provided by the Apple Event Manager
Original Desired
descriptor type descriptor type Description
typeChar typeLongInteger Any string that is a valid
typeShortInteger representation of a number
typeLongFloat can be coerced into an
typeShortFloat equivalent numeric value.
typeExtended
typeComp
typeMagnitude
typeLongInteger typeChar Any numeric descriptor type
typeShortInteger can be coerced into
typeLongFloat the equivalent text string.
typeShortFloat
typeExtended
typeComp
typeMagnitude
Any numeric descriptor type
typeLongInteger typeLongInteger can be coerced into any other
typeTrue typeBoolean The result is the Boolean value
TRUE.
typeFalse typeBoolean The result is the Boolean value
FALSE.
typeEnumerated typeBoolean The enumerated value 'true'
becomes the Boolean value
TRUE. The enumerated value
'fals' becomes the Boolean
value FALSE.
typeBoolean typeEnumerated The Boolean value FALSE
becomes the enumerated value
'fals'. The Boolean value
TRUE becomes the enumerated
value 'true'.
typeShortInteger typeBoolean A value of 1 becomes the
Boolean value TRUE. A value
of 0 becomes the Boolean
value FALSE.
typeBoolean typeShortInteger A value of FALSE becomes 0.
A value of TRUE becomes 1.
continued
Table 2-1 Coercion handling provided by the Apple Event Manager (continued)
Original Desired
descriptor type descriptor type Description
typeAlias typeFSS An alias record is coerced into a
file system specification record.
typeAppleEvent typeAppParameters An Apple event is coerced into a
list of application parameters for
the LaunchParamBlockRec
parameter block.
any descriptor type typeAEList A descriptor record is coerced
into a descriptor list containing a
single item.
typeAEList type of list item A descriptor list containing a
single descriptor record is
coerced into a descriptor record.
Writing Object Accessor Functions
Most of the Apple events in the Core suite and the functional-area suites defined in the Apple Event Registry: Standard Suites can include parameters that consist of object specifier records. If the direct parameter for an Apple event consists of an object specifier record, your handler for the event should call the AEResolve function to resolve the object specifier record: that is, to find the Apple event objects it describes and, if necessary, their properties. The AEResolve function resolves object specifier records with the help of object accessor functions provided by your application. For an overview of the way AEResolve works with object accessor functions, see “Resolving Object Specifier Records,” which begins on page 2-53.
This section describes how write object accessor functions. You need to read this section only if your application supports the Core suite or any of the functional area suites in the Apple Event Registry: Standard Suites.
Your application should provide object accessor functions that can find Apple event objects and their properties for all object classes supported by your application, including their corresponding properties and element classes. Since the Apple Event Manager dispatches object accessor functions according to the class ID of the requested Apple event object and the descriptor type of the token that identifies its container, you have a great deal of flexibility in deciding what object accessor functions you need to write for your application. The installation and dispatching of object accessor functions is described in “Installing Entries in the Object Accessor Dispatch Tables,” which begins on page 2-66.
For example, if your application is a word processor, one object accessor function will probably work equally well for Apple event objects of object classes cParagraph, cItem, and cWord located in containers identified by tokens of descriptor type myTextToken. If you use a single descriptor type for tokens that identify any containers in which Apple event objects of these three object classes can be found, you can dispatch requests for all such elements to the same object accessor function. However, the same word processor might use one descriptor type for tokens identifying containers of class cCell and another descriptor type for tokens identifying containers of class cColumn—in which case it would need an object accessor function for each descriptor type.
For each object class that your application supports, your application should also provide one object accessor function that can find all the properties of that object class, or one object accessor function that can find all the properties of several object classes.
Here’s the declaration for a sample object accessor function:
FUNCTION MyObjectAccessor (desiredClass: DescType;
containerToken: AEDesc;
containerClass: DescType;
keyForm: DescType; keyData: AEDesc;
VAR theToken: AEDesc;
theRefCon: LongInt): OSErr;
When the AEResolve function calls your object accessor function, it passes your function the object class ID of the requested Apple event objects, the object class of their container, a token that identifies the specific container in which to look for them, the key form and key data that specify how to locate them, and the reference constant associated with the object accessor function. Your object accessor function uses this information to locate the requested Apple event objects.
A simple object specifier record always identifies either a single property (by property ID) or a single element in a container (by name or by absolute position). Therefore, if your application supports only simple object specifier records, the object accessor functions it provides need to support only the formPropertyID, formName, and formAbsolutePosition key forms.
A complex object specifier record can specify any number of Apple event objects using relative positions, tests, or ranges. If your application supports complex object specifier records, the object accessor functions it provides should support the key forms formRelativePosition, formRange, and formTest as well as the key forms used with simple object specifier records. In addition, you can optionally provide support for the key form formWhose. “Supporting Whose Descriptor Records” on page 2-170 explains how the key form formWhose can simplify the resolution of object specifier records for elements that belong to a larger group of elements that pass a test.
If your object accessor function successfully locates the requested Apple event objects, your application should return the noErr result code and a token that identifies the requested Apple event objects. The token can be of any descriptor type, as long as it is a descriptor record. For example, to identify a file, your application might use a descriptor record with the descriptor type typeAlias or typeFSS. To identify an open document, your application might define its own descriptor type, such as typeMyDocToken, that contains a handle to a document record.
If your object accessor function does not find the desired Apple event object, it should return the result code errAEEeventNotHandled as its function result, if no other error occurred.
Object accessor functions must not have side effects that change the number or order of elements in a container while an object specifier record is being resolved. If the number of elements in a container is changed during the resolution of an object specifier record, the Apple Event Manager may not be able to locate all the elements.<36pt\>\x12 <8bat\>s
Writing Object Accessor Functions That Find Apple Event Objects
The first three listings in this section demonstrate how to write three object accessor functions that might be called in the following situation: An application receives a Get Data event with a direct parameter that consists of an object specifier record for the first word in the third paragraph of a document. The application’s handler for the Get Data event calls the AEResolve function to resolve the object specifier record. The AEResolve function first calls the application’s object accessor function for Apple event objects of object class of cDocument in containers identified by a token of descriptor type of typeNull.
The AEResolve function passes these parameters to the MyFindDocumentObjectAccessor function shown in Listing 2-35: the constant cDocument in the desiredClass parameter; the constant typeNull in the containerClass parameter; a descriptor record with a descriptor type of type typeNull and a NIL data handle in the containerToken parameter; the constant formName in the keyForm parameter; a descriptor record with a descriptor type of typeText and data that consists of the string "MyDoc" in the keyData parameter; and the reference constant specified in the application’s object accessor dispatch table.
Listing 2-33 An object accessor function that locates Apple event objects of object class cDocument by name
The MyFindDocumentObjectAccessor function uses the information in the keyForm and keyData parameters to find the specified document. If the MyFindDocumentObjectAccessor function finds the Apple event object, it returns a token with the application-defined descriptor type typeMyDocToken that identifies the document. The application defines the typeMyDocToken descriptor type as a descriptor record that contains a handle to a document record. The MyFindDocumentObjectAccessor function returns this token and the noErr result code to the AEResolve function.
In the Get Data example, the token returned to AEResolve by the MyFindDocumentObjectAccessor function identifies the document “MyDoc.” The AEResolve function then calls the application’s object accessor function for Apple event objects of object class cParagraph in containers identified by a token of descriptor type of typeMyDocToken.
In this case, the AEResolve function passes these parameters to the MyFindParaObjectAccessor function shown in Listing 2-34: the constant cParagraph in the desiredClass parameter; the constant cDocument in the containerClass parameter; the token returned by the MyFindDocumentObjectAccessor function (a descriptor record with the typeMyDocToken descriptor type and handle to a document record) in the containerToken parameter; the constant formAbsolutePosition in the keyForm parameter; a descriptor record with the typeLongInteger descriptor type and data that consists of the value 3 (indicating the third paragraph) in the keyData parameter; and the reference constant specified in the application’s object accessor dispatch table.
Listing 2-34 An object accessor function that locates Apple event objects of object class cParagraph
FUNCTION MyFindParaObjectAccessor (desiredClass: DescType;
containerClass: DescType;
containerToken: AEDesc;
keyForm: DescType; keyData:
AEDesc; VAR token: AEDesc;
theRefCon: LongInt): OSErr;
VAR
paraNumber: LongInt;
{myFoundTextRecord is an application-defined data type, }
{ consisting of two fields (paraStart and paraEnd)}
foundParaRec: myFoundTextRecord;
foundParaStart:LongInt;
foundParaEnd: LongInt;
BEGIN
IF keyForm = formAbsolutePosition THEN
BEGIN
{get the index of the paragraph from the key data}
MyGetIndexFromDesc(keyData, index);
{Get the desired paragraph by index}
MyGetPara(index, containerToken, foundParaStart,
foundParaEnd);
IF foundParaStart = 0 THEN
MyFindParaObjectAccessor := gObjectNotFound
ELSE {create token that identifies the paragraph}
BEGIN
foundParaRec.paraStart := foundParaStart;
foundParaRec.paraEnd := foundParaEnd;
MyFindParaObjectAccessor :=
AECreateDesc(typeMyParaToken, @foundParaRec,
SizeOf(foundParaRec), token);
END;
END
{handle the other key forms you support}
ELSE
MyFindParaObjectAccessor := kKeyFormNotSupported
END;
The MyFindParaObjectAccessor function uses another application-defined function, MyGetPara, to search the data structures associated with the document and find the desired paragraph. (The document is specified by the containerToken parameter.) If the MyGetPara function finds the Apple event object, it returns a pointer to the beginning of the paragraph and a pointer to the end of the paragraph. The MyFindParaObjectAccessor function returns a token with the application-defined descriptor type typeMyParaToken that identifies the requested paragraph. The application defines the typeMyParaToken descriptor type as a descriptor record that contains pointers to the beginning and ending locations of the paragraph. The MyFindParaObjectAccessor function returns this token and the noErr result code to the AEResolve function.
In the Get Data example, the token returned to AEResolve by the MyFindParaObjectAccessor function identifies the third paragraph in the document “MyDoc.” The AEResolve function then calls the application’s object accessor function for Apple event objects of object class cWord in containers identified by a token of descriptor type typeMyParaToken.
In this case, the AEResolve function passes these parameters to the MyFindWordObjectAccessor function shown in Listing 2-35: the constant cWord as the desiredClass parameter; the constant cParagraph as the containerClass parameter; the token returned by the MyFindParagraphObjectAccessor function (a descriptor record with the typeMyParaToken descriptor type and handle to a paragraph record) in the container parameter; the constant formAbsolutePosition in the keyForm parameter; a descriptor record with the typeLongInteger descriptor type and data that consists of the value 1 (indicating the first word) in the keyData parameter; and the reference constant specified in the application’s object accessor dispatch table.
The MyFindWordObjectAccessor function uses another application-defined function, MyGetWord, to search the paragraph to find the desired word. (The paragraph is specified by the containerToken parameter.) If the MyGetWord function finds the Apple event object, it returns a pointer to the beginning of the word and a pointer to the end of the word (or it could return a string). The MyFindWordObjectAccessor function then creates a token with the application-defined descriptor type typeMyWordToken that identifies the requested word. The application defines the typeMyWordToken descriptor type as a descriptor record that contains in its data field pointers to the beginning and ending locations of the word (or it could be defined as a string). The MyFindWordObjectAccessor function returns this token and the noErr result code to the AEResolve function, which in turn returns the token to the application’s handler for the Get Data event that originally called AEResolve.
Listing 2-35 An object accessor function that locates Apple event objects of object class cWord
FUNCTION MyFindWordObjectAccessor
(desiredClass: DescType;
containerType: DescType;
containerToken: AEDesc;
keyForm: DescType; keyData: AEDesc;
VAR token: AEDesc;
theRefCon: LongInt): OSErr;
VAR
wordNumber: LongInt;
foundWordRec: myFoundTextRecord;
foundWordStart: LongInt;
foundWordEnd: LongInt;
BEGIN
IF keyForm = formAbsolutePosition THEN
BEGIN
{get the index of the word from the key data}
MyGetIndexFromDesc(keyData, index);
{Get the desired word by index}
MyGetWord(index, containerToken, foundWordStart,
foundWordEnd);
IF foundWordStart = 0 THEN
MyFindWordObjectAccessor := gObjectNotFound
ELSE {create token that identifies the paragraph}
BEGIN
foundWordRec.start := foundWordStart;
foundWordRec.end := foundWordEnd;
MyFindWordObjectAccessor :=
AECreateDesc(typeMyWordToken, @foundWordRec,
SizeOf(foundWordRec), token);
END;
END
{handle the other key forms you support}
ELSE
MyFindWordObjectAccessor := kKeyFormNotSupported
END;
Listing 2-33 shows an object accessor function that locates a document in the default container. Every application must provide one or more object accessor functions that can find Apple event objects in the default container, which is always identified by a descriptor record of descriptor type typeNull. Listing 2-36 provides another example of an object accessor function that locates an Apple event object in the default container. If the MyFindWindowObjectAccessor function shown in Listing 2-36 were installed in an application’s object accessor dispatch table, the AEResolve function would call it whenever AEResolve needed to locate an Apple event object of the object class cWindow in a container identified by a token of descriptor type typeNull.
Listing 2-36 An object accessor function that locates Apple event objects of the object class cWindow
FUNCTION MyFindWindowObjectAccessor (desiredClass: DescType;
containerClass: DescType;
containerToken: AEDesc;
keyForm: DescType; keyData: AEDesc;
VAR token: AEDesc;
theRefCon: LongInt): OSErr;
VAR
windowName: Str255;
actSize: Size;
windTitle: Str255;
window: WindowPtr;
index: Integer;
iLoop: Integer;
found: Boolean;
BEGIN
IF keyForm = formName THEN
BEGIN
{get the name of the window to find from the keyData }
{ parameter. MyGetStringFromDesc gets data out of an }
{ AEDesc and returns a string and the string’s size}
IF EqualString(windTitle, windowName, FALSE, TRUE)
THEN
found := TRUE; {found it!}
IF (found = FALSE) THEN
window :=
WindowPtr(WindowPeek(window)^.nextWindow);
END; {of while}
IF window = NIL THEN
MyFindWindowObjectAccessor := gObjectNotFound
ELSE {create token that identifies the window}
MyFindWindowObjectAccessor := AECreateDesc
(typeMyWindow, @window, SizeOf(window), token);
END; {of formName}
IF keyForm = formAbsolutePosition THEN
{find the window given an index in key data}
BEGIN {get the index from the key data}
MyGetIndexFromDesc(keyData, index);
iLoop := 0;
window := FrontWindow;
WHILE (window <> NIL) AND (found <> TRUE) DO
BEGIN
iLoop := iLoop +1;
IF iLoop = index THEN
found := TRUE
ELSE
window :=
WindowPtr(WindowPeek(window)^.nextWindow);
END; {of while}
IF window = NIL THEN
MyFindWindowObjectAccessor := gObjectNotFound
ELSE {create token that identifies the window}
MyFindWindowObjectAccessor :=
AECreateDesc(typeMyWindow, @window,
SizeOf(window), token);
END {of formAbsolutePosition}
{handle the other key forms you support}
ELSE
MyFindWordObjectAccessor := kKeyFormNotSupported
END;
The keyForm parameter of the MyWindowObjectAccessor function describes how the function should interpret the keyData parameter. If the key form is formName, then the key data contains the name of the window to locate. If the key form is formAbsolutePostion, the key data contains the position of the window in the window list to locate; for example, key data of 1 identifies the frontmost window.
The MyWindowObjectAccessor function only supports the formName and formAbsolutePosition key words. Your object accessor functions should support all key forms that make sense for the object classes whose Apple event objects it can locate.
For the formName key word, the MyWindowObjectAccessor function starts with the frontmost window and compares the window’s title to the name specified by the keyData parameter. It continues this search until either the end of the window list is reached or a match is found. If the MyWindowObjectAccessor function finds a match, it uses the AECreateDesc function to create a descriptor record for the token, specifying the application-defined typeMyWindow descriptor type and the data for this descriptor type as a window pointer.
The MyWindowObjectAccessor function then sets its function result appropriately, and the AEResolve function either returns this function result and token, or uses the returned token to request the next Apple event object in the container hierarchy, such as a document in the window.
Writing Object Accessor Functions That Find Properties
The Apple event object to which a property belongs is that property’s container. Your application should provide an object accessor function for finding properties in containers identified by tokens of various descriptor types. Your application does not need to be given a property’s specific object class in order to find that property; instead, you can specify the object class ID for any property with the constant cProperty. This means you can write a single object accessor function that can find any property of a container identified by a token of a given descriptor type.
To specify such an object accessor function, you can add a single entry to the object accessor dispatch table that specifies the desired object class as cProperty for a given token descriptor type. For example, Listing 2-37 shows an object accessor function that finds any property of any Apple event object identified by a token of type typeMyWindowProp.
Listing 2-37 An object accessor function that finds any property of an Apple event object identified by a token of descriptor type typeMyWindow
It is up to you to decide how many token descriptor types you need to define for your application. In many cases you may be able to define one token that can identify Apple event objects of several different object classes, such as a typeMyText token that identifies Apple event objects of object classes cText, cWord, cItem, and cChar. In other cases you may need to define specific token descriptor types for specific object classes.
For example, the MyFindDocumentObjectAccessor routine shown in Listing 2-33 on page 2-160 returns a token of descriptor type typeMyDocToken, which contains a document record:
CONST {application-defined token}
typeMyDocToken = 'docr'; {a document record}
Descriptor record for an application-defined token that identifies a document
The MyFindPropertyOfWindowObjectAccessor routine shown in Listing 2-37 returns a token of descriptor type typeMyWindowProp for every property that it can locate:
CONST {application-defined token}
typeMyWindowProp = 'wprp'; {a window pointer and a }
{ property ID}
Descriptor record for an application-defined token that identifies a property
When an object accessor function that supports key form formRange locates a range of Apple event objects, it should normally return a descriptor list (AEDescList) of tokens for the individual objects. However, an object accessor function that returns a range of text should usually return a single token representing the whole range; for example, it makes more sense to return a single token that identifies a range of text from character 3 to character 17 rather than a group of tokens that each represent one character.
A token is valid only until the Apple Event Manager has located the requested element in the container the token represents and returned another token for the element. The Apple Event Manager disposes of tokens it obtains while resolving an object specifier record, but one token is always left over—the token that identifies the specified Apple event object or objects. Your application should dispose of this final token by calling the AEDisposeToken function, which in turn calls your application’s token disposal function (if it has one), an optional object callback function that disposes of a token. A declaration for a token disposal function is described on page 2-260.
If your application does not provide a token disposal function, the Apple Event Manager uses the AEDisposeDesc function to dispose of a descriptor record. For some applications, disposing of tokens may involve more than simply disposing of a descriptor record, and may therefore require a custom token disposal function. For example, the data field of a token descriptor record might contain a handle to a block that in turn contains references to storage for the Apple event object referred to by the token. These applications can provide a token disposal function that performs the additional tasks that are necessary.
Supporting Whose Descriptor Records
An object specifier record with the key form formWhose is never created directly by an application. Instead, the Apple Event Manager collapses the key form and key data from two object specifier records in a container hierarchy into one object specifier record with the key form formWhose and key data that consists of a whose descriptor record, a descriptor record of descriptor type typeWhoseDescriptor. The target application can often locate Apple event objecst more efficiently with a whose descriptor record than would otherwise be possible. For example, Figure 2-24 on page 2-137 shows four object specifier records that specify the container hierarchy for the first row in the table “MyAddresses” of the database “GigaBase” that meets a test. A server application might be able to locate the requested row more quickly if it could simply test each table until it finds the first one that passes the test, rather than identifying all the tables that pass the test and then locating the first one in that group.
Support for whose descriptor records is optional, and is useful only for applications that can make use of a test combined with either an absolute position or a range to locate Apple event objects. If you want the Apple Event Manager to pass your application object specifier records of type formWhose whenever possible, you must set the kAEIDoWhose flag in the callBackFlags parameter of the AEResolve function. If for any reason your application cannot handle a particular whose descriptor record, it should return errAEEventNotHandled as the result code, and the Apple Event Manager will try again using the original object specifier records.
If a server application that supports whose descriptor records receives an object specifier record with the container hierarchy shown in Figure 2-24, the Apple Event Manager will automatically collapse the four nested object specifier records into three, as shown in Figure 2-28.
A container hierarchy created by the Apple Event Manager for a server application that supports whose descriptor records
A whose descriptor record is a coerced AE record that consists of two keyword-specified descriptor records with the following keywords:
Keyword Description
keyAEIndex A descriptor record of either type typeLongInteger or type typeAbsoluteOrdinal specifying an absolute position among those Apple event objects that pass the test; or a descriptor record of type typeWhoseRange specifying a range of Apple event objects that pass the test.
keyAETest A descriptor record of either type typeCompDescriptor or type typeLogicalDescriptor that specifies a test.
If the Apple Event Manager encounters a range descriptor record that specifies a range of Apple event objects that pass a test, it will, under certain conditions, coerce the range descriptor record to a whose range descriptor record. A whose range descriptor record is a coerced AE record of typeWhoseRange that consists of two keyword-specified descriptor records with the following keywords:
Keyword Description
keyAEWhoseRangeStart A descriptor record of either type typeLongInteger or type typeAbsoluteOrdinal specifying the absolute position of the Apple event object, within the set of all elements that pass a test, that identifies the beginning of the desired range.
keyAEWhoseRangeStop A descriptor record of either type typeLongInteger or type typeAbsoluteOrdinal specifying the absolute position of the Apple event object, within the set of all elements that pass a test, that identifies the end of the desired range.
When resolving an object specifier record for a target application that supports formWhose, the Apple Event Manager will coerce a range descriptor record to a whose range descriptor record if the container for the specified range of Apple event objects is a group of Apple event objects that pass a test, and if the boundary objects in the original range descriptor record meet three conditions:
n Both boundary objects are of the same object class as the Apple event objects in the range they specify.
n The object specifier record for each boundary object specifies its container with a descriptor record of descriptor type typeCurrentContainer.
n The object specifier record for each boundary object specifies a key form of formAbsolutePosition.
When your application receives a request for an Apple event object identified by a key form of formWhose, the appropriate object accessor function in your application must coerce the whose descriptor record specified as the key data to an AE record and extract the data from the AE record using the AEGetKeyPtr and AEGetKeyDesc routines. If the keyword-specified descriptor record with the keyword keyAEIndex consists of a descriptor record of descriptor type typeWhoseRange, your object accessor function must also coerce that descriptor record to an AE record and extract the data. Your object accessor function should then attempt to locate the requested Apple event objects and, if successful, return a token that identifies them.
Writing Object Callback Functions
If an Apple event parameter consists of an object specifier record, your handler for the Apple event typically calls AEResolve to begin the process of locating the requested Apple event object or objects. AEResolve in turn calls object accessor functions and, if necessary, object callback functions provided by your application.
Every application that supports Apple event objects should provide object accessor functions that can locate Apple event objects belonging to any of the supported object classes. For an overview of the way AEResolve calls object accessor functions in order to locate Apple event objects described by object specifier records, see “Resolving Object Specifier Records,” which begins on page 2-53.
In addition to object accessor functions, your application can provide up to seven object callback functions:
n An object-counting function counts the number of elements of a specified class in a specified container, so that the Apple Event Manager can determine how many elements it must examine to find the element or elements that pass a test. Your application must provide one object-counting function if it supports complex object specifier records. For information on writing an object-counting function, see “Writing an Object-Counting Function,” which begins on page 2-175.
n An object comparison function compares one element to either another element or to a descriptor record and returns either TRUE or FALSE. Your application must provide one object comparison function if it supports complex object specifier records. For information on writing an object comparison function, see “Writing an Object Comparison Function,” which begins on page 2-177.
n A token disposal function disposes of a token after your application calls the AEDisposeToken function. If your application doesn’t provide a token disposal function, the Apple Event Manager uses the AEDisposeDesc function instead. Your application must provide one token disposal function if it supports object marking or if it requires more than a call to AEDisposeDesc to dispose of one of its tokens. The declaration for a token disposal function is described on page 2-260.
n An error callback function gives the Apple Event Manager an address to which to write the descriptor record it is currently working with if an error occurs while AEResolve is attempting to resolve an object specifier record. Your application is not required to provide an error callback function. The declaration for an error callback function is described on page 2-260.
n Three marking callback functions are used by the Apple Event Manager to get a mark token from your application, to mark specific Apple event objects, and to adjust the marks on a group of marked Apple event objects. Your application must provide all three marking functions if it supports marking. For information on writing marking functions, see “Writing Marking Callback Functions,” which begins on page 2-179.
To make your object callback functions available to the Apple Event Manager, use the AESetObjectCallbacks function:
Each parameter to the AESetObjectCallbacks function consists of either a pointer to the corresponding application-defined function or NIL if no function is provided. AESetObjectCallbacks sets object callback functions that are available only to your application. To set system object callback functions, which are available to all applications and processes running on the same computer, use the AEInstallSpecialHandler function as described on page 2-251.
If your application supports complex object specifier records, it should provide an object-counting function and an object comparison function. The Apple Event Manager calls your application’s object-counting function in order to determine the number of Apple event objects in a specified container that need to be tested. The Apple Event Manager calls your application’s object comparison function when it needs to compare one Apple event object to either another Apple event object or to a value in a descriptor record.
If your application does not provide a token disposal function, the Apple Event Manager uses the AEDisposeDesc function to dispose of a token. But for some applications, disposing of tokens may involve more than simply disposing of a descriptor record, and may therefore require a custom token disposal function. For example, the data field of a token descriptor record might contain a handle to a block that in turn contains references to storage for the Apple event object referred to by the token. These applications can provide a token disposal function that performs the additional tasks that are necessary.
Whenever more than one Apple event object passes a test, AEResolve can either return a list of tokens or make use of a target application’s ability to mark its own objects. Sometimes a list of tokens can become unmanageably large. For example, if a Get Data event asks for the names and addresses of all customers with a specified zip code who have purchased a specified product, the object accessor function that locates all the customers with the specified zip code might return a list of many thousands of tokens; the elements identified by those tokens would then have to be tested for the specified product. However, if your application uses some method of marking objects, you can choose simply to mark the requested objects rather than returning a list of tokens. “Writing Marking Callback Functions” on page 2-179 describes how to do this. If you provide marking functions, you must also provide a token disposal function.
When one of your application’s Apple event handlers calls the AEResolve function, the handler should pass a value in the second parameter that specifies whether your application supports whose descriptor records or provides marking callback functions. You can add the following constants, as appropriate, to provide a value for the second parameter:
CONST kAEIDoMinimum = $0000 ; {Does not provide callbacks}
kAEIDoWhose = $0001 ; {Supports key form formWhose}
For example, this code instructs the Apple Event Manager to call any marking functions previously set with the AESetObjectCallbacks function while resolving the object specifier record in the objectSpecifier parameter:
If your application supports Apple event objects that can contain more than one element, you must provide an object-counting function. Your object-counting function should be able to count the number of elements of a given object class in a given container. For example, if your application supports Apple event objects that belong to the object class cText in the Text suite, your application should provide an object-counting function that can count Apple event objects of each element class listed in the definition of cText in the Apple Event Registry: Standard Suites. In this case, your application should provide an object-counting function that can count the number of words, items, or characters in a text object.
You specify your object-counting function with the AESetObjectCallbacks function. Once you set your object-counting function, the Apple Event Manager calls your object-counting function whenever it is resolving an object specifier record and it requires a count of the number of elements in a given container.
Here’s the declaration for a sample object-counting function:
FUNCTION MyCountObjects (desiredClass: DescType;
containerClass: DescType;
containerToken: AEDesc;
VAR result: LongInt): OSErr;
When the Apple Event Manager calls your object-counting function, it passes the object class ID of the Apple event objects to count, the object class of their container, and a token identifying their container. (The container class can be useful if you want to use one token type for several object classes.) Your object-counting function uses this information to count the number of Apple event objects of the specified object class in the specified container. After counting the Apple event objects, your application should return the noErr result code and should also return the number of Apple event objects counted in the result parameter.
Listing 2-38 shows an application-defined function, MyCountObjects, that counts the number of objects for any object class supported by the application.
{this app does not support any other object classes}
IF (desiredClass <> cWindow) AND (desiredClass <> cWord AND
(desiredClass <> cParagraph) THEN
MyCountObjects := kObjectClassNotFound
ELSE
MyCountObjects := myErr;
END;
Writing an Object Comparison Function
If your application supports complex object specifier records, you must provide an object comparison function. Your object comparison function should be able to compare one Apple event object to another Apple event object or to another descriptor record. For example, if your application supports the formTest key form, which can be used with the key data in an object specifier record to compare elements of a given container with a given Apple event object or the contents of a given descriptor record, your application should provide an object comparison function.
You specify your object comparison function to the Apple Event Manager using the AESetObjectCallbacks function. Once you set your object comparison function, the Apple Event Manager calls your object comparison function whenever it is resolving Apple event objects and needs to test or compare the value of an Apple event object with another Apple event object or descriptor record.
Here’s the declaration for a sample object comparison function:
FUNCTION MyCompareObjects (comparisonOperator: DescType;
object: AEDesc;
objectOrDescToCompare: AEDesc;
VAR result: Boolean): OSErr;
When the Apple Event Manager calls your object comparison function, it passes a comparison operator that specifies how the two objects should be compared, the object specifier record that describes the first Apple event object, and either an object specifier record that describes the Apple event object to compare or a descriptor record.
It is up to your application to interpret the comparison operators it receives. The meaning of comparison operators differs depending on the Apple event objects being compared, and not all comparison operators apply to all object classes. After successfully comparing the Apple event objects, your object comparison function should return the noErr result code and should also return a Boolean value in the result parameter, specifying TRUE if the result of the comparison is true, and FALSE otherwise. If for any reason your comparison function is unable to compare the specified Apple event objects, it should return the result code errAEEventNotHandled; then the Apple Event Manager will try an alternative method of comparing the Apple event objects, such as calling the equivalent system object comparison function, if one exists.
Your object comparison function should be able to compare an Apple event object belonging to any object class supported by your application with another Apple event object. Your object comparison function should also be able to compare two Apple event objects with different object classes if appropriate. For example, an object comparison function for a word processing application might be asked to compare the First Name column of a specified row in a table with the first word on a specified page—that is, to compare an Apple event object of object class cColumn with an Apple event object of object class cWord. You must decide what kinds of comparisons make sense for your applicatio.
The Apple Event Registry: Standard Suites defines standard comparison operators. Here is a list of the constants that correspond to these comparison operators:
CONST
kAEGreaterThan = '>= '; {the value of the first }
{ operand is greater than the }
{ value of the second operand}
kAEGreaterThanEquals = '> '; {the value of the first }
{ operand is greater than or }
{ equal to the value of the }
{ second operand}
kAEEquals = '= '; {the value of the first }
{ operand equals the value of }
{ the second operand}
kAELessThan = '< '; {the value of the first }
{ operand is less than the }
{ value of the second operand}
kAELessThanEquals = '<= '; {the value of the first }
{ operand is less than or }
{ equal to the value of the }
{ second operand}
kAEBeginsWith = 'bgwt'; {the value of the first }
{ operand begins with the }
{ value of the second operand}
kAEEndsWith = 'ends'; { the value of the first }
{ operand ends with the value }
{ of the second operand}
kAEContains = 'cont'; {the value of the first }
{ operand contains the value }
{ of the second operand}
Listing 2-39 shows an application-defined function, MyCompareObjects, that compares two Apple event objects of any object class supported by the application.
Object comparison function that compares two Apple event objects
FUNCTION MyCompareObjects (comparisonOperator: DescType;
object: AEDesc;
objectOrDescToCompare: AEDesc;
VAR result: Boolean): OSErr;
VAR
myErr: OSErr;
BEGIN
result := FALSE;
IF comparisonOperator = kAEEquals THEN
BEGIN {compare two objects for equivalence}
result := MyCompEquals(object, objectOrDescToCompare);
END; {of kAEEquals}
IF comparisonOperator = kAEGreaterThan THEN
BEGIN {compare two objects}
result := MyCompGreaterThan(object, objectOrDescToCompare);
END; {of kAEGreaterThan}
IF comparisonOperator = kAELessThan THEN
BEGIN {compare two objects}
result := MyCompLessThan(object, objectOrDescToCompare);
END; {of kAELessThan}
{this app does not support any other comparison operators}
IF result = TRUE THEN
MyCompareObjects := noErr
ELSE
MyCompareObjects := errAEEventNotHandled;
END;
The MyCompareObjects function calls a separate application-defined routine for each comparison operator. In each case, the application-defined routine that actually performs the comparison can compare an Apple event object with either another Apple event object or with a descriptor record’s data. If for any reason the comparison cannot be performed, the MyCompareObjects functions returns the result code errAEEventNotHandled.
Writing Marking Callback Functions
Marking callback functions allow applications such as databases that can mark their own objects to take advantage of that capability when resolving object specifier records. Instead of returning a list of tokens for a group of Apple event objects that pass a test, your application can simply mark the Apple event objects and return a token that identifies how they have been marked. This can both speed up the resolution of complex object specifier records and reduce the amount of memory you need to allocate for tokens.
The use of marking callback functions is optional, and only makes sense if you can reasonably expect that the tokens created in the process of resolving some object specifier records might not all fit in memory at once, and if your application already uses a marking mechanism. If you want the Apple Event Manager to use marking callback functions provided by your application, you must add the kAEIDoMarking constant to the value of the callBackFlags parameter for the AEResolve function. If for any reason your application cannot mark a requested set of Apple event objects, it should return eventNotHandled as the result code, and the Apple Event Manager will attempt to continue resolving the object specifier record by some other method, such as using a system marking function, if one exists, or using object accessor functions without calling marking callback functions.
If your application supports marking callback functions, it must provide three functions with declarations modeled after these samples:
FUNCTION MyGetMarkToken (containerToken: AEDesc;
containerClass: DescType;
VAR Result: AEDesc): OSErr;
FUNCTION MyMark (theToken: AEDesc; markToken: AEDesc;
markCount: LongInt): OSErr;
FUNCTION MyAdjustMarks (newStart,newStop: LongInt;
markToken: AEDesc): OSErr;
For more detailed information about these sample declarations, see “Object Callback Functions,” which begins on page 2-256.
To resolve a given object specifier record with the aid of the marking callback functions provided by your application, the Apple Event Manager first calls your application’s mark token function (MyGetMarkToken), passing a token that identifies the container of the elements to be marked in the containerToken parameter and the container’s object class in the containerClass parameter. The mark token function returns a mark token. A mark token, like other tokens, can be a descriptor record of any type; however, unlike other tokens, it identifies the way your application will mark Apple event objects during the current session while resolving a single test. A mark token does not identify a specific Apple event object; rather, it contains information for the use of your application that specifies how one or more Apple event objects are marked.
After it receives the mark token, the Apple Event Manager can call your application’s object-marking function (MyMark) repeatedly to mark specific Apple event objects. The Apple Event Manager passes the marking function a token for the object to be marked (obtained from the appropriate object accessor function) in the theToken parameter; the current mark token in the markToken parameter; and the mark count in the markCount parameter. The mark count indicates the number of times the Apple Event Manager has called the marking function for the current mark token. Your application should record the mark count at the time each Apple event object is marked. The mark count recorded for each marked Apple event object allows your application to distinguish one set of marked objects from another when a single object specifier record specifies more than one test.
When the Apple Event Manager needs to identify either a range of elements or the absolute position of an element in a group of Apple event objects that pass a test, it can use your applications’ mark-adjusting function (MyAdjustMarks) to unmark objects that it has previously marked with your marking function . For example, if an object specfier record specifies “any row in the table ‘My Customers’ for which the City column is ‘San Francisco’,” the Apple Event Manager first uses the appropriate object accessor routine to locate all the rows in the table for which the City column is “San Francisco,” and calls the application’s marking function repeatedly to mark them; it then generates a random number between 1 and the number of rows it found that passed the test, and calls the application’s mark-adjusting function to unmark all the rows whose mark count does not match the randomly generated number. If the randomly chosen row has a mark count value of 5, the Apple Event Manager passes the mark-adjusting function 5 in both the newStart parameter and the newStop parameter, and the current mark token in the markToken parameter. The newStart and newStop parameters identify the beginning and end of the new set of marked objects that the mark-adjusting function will create by unmarking those previously marked objects that are not included in the new set. When the Apple Event Manager calls your mark-adjusting function, your application must dispose of any data structures that it may have created in order to mark the previously marked objects. The Apple Event Manager will call your mark-adjusting function only once for a given mark token.
A mark token is valid until the Apple Event Manager either disposes of it (by calling AEDisposeToken) or returns it as the result of the AEResolve function. If the final result of a call to the AEResolve function is a mark token, the Apple event objects currently marked for that mark token are those specified by the object specifier record passed to AEResolve, and your application can proceed to do whatever the Apple event has requested. Note that your application is responsible for disposing of a final mark token with a call to AEDisposeToken, just as for any other final token.
If your application supports marking, it should also provide a token disposal function. When the Apple Event Manager calls AEDisposeToken to dispose of a mark token that is not the final result of a call to AEResolve, the subsequent call to your token disposal function lets you know that you can unmark the Apple event objects marked with that mark token. A call to AEDisposeDesc to dispose of a mark token (which would occur if you did not provide a token disposal function) would go unnoticed.
2
2The Apple Event Manager
Reference to the Apple Event Manager
This section describes the basic data structures and all the routines that are specific to the Apple Event Manager. It also provides examples of application-defined object accessor functions and object callback functions that a server application might provide for use by AEResolve in resolving object specifier records. The first section, “Data Structures,” shows the Pascal data structures for the descriptor records and descriptor lists that provide the fundamental building blocks from which an Apple event is constructed. “Apple Event Manager Routines,” which begins on page 2-183, describes the Apple Event Manager routines you use to create, send, receive, and process Apple events. “Application-Defined Functions,” which begins on page 2-254, provides examples of object accessor functions and object callback functions that a server application might provide.
Data Structures
Descriptor records are the fundamental data structures from which Apple events are constructed. A descriptor record is a data structure of type AEDesc:
TYPE AEDesc =
RECORD {descriptor record}
descriptorType: DescType; {type of data being passed}
dataHandle: Handle; {handle to data being passed}
END;
descriptorType A four-character string of type DescType (which in turn is of type ResType) that indicates the type of data being passed.
dataHandle A handle to the data being passed.
Apple event attributes, Apple event parameters, object specifier records, tokens, and almost all the other data structures defined by the Apple Event Manager consist of one or more descriptor records. The Apple Event Manager identifies the various components of an Apple event by means of keywords associated with the corresponding descriptor records. The AEKeyword data type is defined as a four-character code:
TYPE AEKeyword = PACKED ARRAY[1..4] OF Char;
Constants are typically used for keywords. A keyword combined with a descriptor record forms a keyword-specified descriptor record, which is defined by a data structure of type AEKeyDesc:
TYPE AEKeyDesc =
RECORD
descKey: AEKeyword; {keyword}
descContent: AEDesc; {descriptor record}
END;
descKey A four-character code of type AEKeyword that identifies the data in the descContent field.
descContent A descriptor record of type AEDesc.
Most the other data structures defined by the Apple Event Manager consist of combinations of descriptor records and keyword-specified descriptor records. For information about specific keywords and the data structures constructed or coerced from descriptor records of type AEDesc, see “Data Structures Within Apple Events,” which begins on page 2-17. Other data structures defined by the AppleEvent Manager are described in the next section, “Apple Event Manager Routines,” under the routines that use them.
Apple Event Manager Routines
This section describes routines for creating and managing Apple event and object accessor dispatch tables, getting information from Apple events, creating Apple events, creating and resolving object specifier records, sending Apple events, disposing of descriptor records and tokens, and coercing descriptor types.
Creating and Managing the Apple Event Dispatch Tables
An Apple event dispatch table contains entries that specify the event class and event ID that refer to one or more Apple events, the address of the handler routine that handles those Apple events, and a reference constant. You can use the AEInstallEventHandler function to add entries to the Apple event dispatch table. This function sets up the initial mapping between the handlers in your application and the Apple events that they handle.
To get the address of a handler currently in the Apple event dispatch table, use the AEGetEventHandler function. If you need to remove any of your Apple event handlers after the mapping is established, you can use the AERemoveEventHandler function.
2AEInstallEventHandler
You can use the AEInstallEventHandler function to add an entry to either your application’s Apple event dispatch table or the system Apple event dispatch table.
FUNCTION AEInstallEventHandler (theAEEventClass: AEEventClass;
theAEEventID: AEEventID;
handler: EventHandlerProcPtr;
handlerRefcon: LongInt;
isSysHandler: Boolean): OSErr;
theAEEventClass
The event class for the Apple event or events to be dispatched for this entry. The AEEventClass data type is defined as a four-character code:
TYPE AEEventClass = PACKED ARRAY[1..4] OF Char;
theAEEventID
The event ID for the Apple event or events to be dispatched for this entry. The AEEventID data type is defined as a four-character code:
TYPE AEEventID = PACKED ARRAY[1..4] OF Char;
handler A pointer to an Apple event handler for this dispatch table entry. Note that a handler in the system dispatch table must reside in the system heap; this means that if the value of the isSysHandler parameter is TRUE, the handler parameter should point to a location in the system heap. Otherwise, if you put your system handler code in your application heap, you must remove the handler before your application terminates by using the AERemoveEventHandler function.
handlerRefcon
A reference constant that is passed by the Apple Event Manager to the handler each time the handler is called. If your handler doesn’t use a reference constant, use 0 as the value of this parameter.
isSysHandler
Specifies the Apple event dispatch table to which you want to add the handler. If the value of isSysHandler is TRUE, the Apple Event Manager adds the handler to the system Apple event dispatch table. Entries in the system Apple event dispatch table are available to all applications. If the value of isSysHandler is FALSE, the Apple Event Manager adds the handler to your application’s Apple event dispatch table. The application’s Apple event dispatch table is searched first; the system Apple event dispatch table is searched only if the necessary handler is not found in your application’s Apple event dispatch table.
DESCRIPTION
AEInstallEventHandler creates an entry in the Apple event dispatch table. You must supply parameters that specify the event class, event ID, and address of the handler routine that handles Apple events of the specified event class and event ID, and whether the handler is to be added to the system Apple event dispatch table or your application’s Apple event dispatch table. You can also specify a reference constant that the Apple Event Manager passes to your handler whenever your handler processes an Apple event.
The parameters theAEEventClass and theAEEventID specify the event class and event ID of the Apple events to be handled by the handler for this dispatch table entry. For these parameters, you must provide one of the following combinations:
n the event class and event ID of a single Apple event to be dispatched to the handler
n the typeWildCard constant for theAEEventClass and an event ID for theAEEventID, which indicates that Apple events from all event classes whose event IDs match theAEEventID should be dispatched to the handler
n an event class for theAEEventClass and the typeWildCard constant for theAEEventID, which indicates that all events from the specified event class should be dispatched to the handler
n the typeWildCard constant for both the theAEEventClass and theAEEventID parameters, which indicates that all Apple events should be dispatched to the handler
If you use the typeWildCard constant for either the theAEEventClass or the theAEEventID parameter (or for both parameters), the corresponding handler must return the error errAEEventNotHandled if it does not handle a particular event.<36pt\>\x12 <8bat\>s
If there was already an entry in the specified Apple event handler dispatch table for the same event class and event ID, it is replaced. Therefore, before installing a handler for a particular Apple event in the system dispatch table, use the AEGetEventHandler function to determine whether the table already contains a handler for that event. If an entry exists, AEGetEventHandler returns a reference constant and a pointer to that event handler. Chain these to your event handler by providing pointers to the previous handler and its reference constant in the handlerRefcon parameter of AEInstallEventHandler. When your handler is finished, use these pointers to call the previous handler. If you remove your system handler, be sure to reinstall the chained handlers.
When an application calls a system Apple event handler, the A5 register is set up for the calling application. For this reason, if you provide a system Apple event handler, it should never use A5 global variables or anything that depends on a particular context; otherwise, the application that calls the system handler may crash.<36pt\>\x12 <8bat\>u
RESULT CODES
noErr 0 No error
paramErr –50 Parameter error (handler pointer is NIL or odd)
memFullErr –108 Not enough room in heap zone
SEE ALSO
For more information about installing Apple event handlers, see “Installing Entries in the Apple Event Dispatch Tables,” which begins on page 2-63.
2AEGetEventHandler
You can use the AEGetEventHandler function to get an entry from an Apple event dispatch table.
FUNCTION AEGetEventHandler (theAEEventClass: AEEventClass;
theAEEventID: AEEventID;
VAR handler: EventHandlerProcPtr;
VAR handlerRefcon: LongInt;
isSysHandler: Boolean): OSErr;
theAEEventClass
The value of the event class field of the dispatch table entry for the desired Apple event handler.
theAEEventID
The value of the event ID field of the dispatch table entry for the desired Apple event handler.
handler TheAEGetEventHandler function returns a pointer to the desired Apple event handler in this parameter.
handlerRefcon
The AEGetEventHandler function returns the reference constant from the object accessor dispatch table entry for the specified Apple event handler in this parameter.
isSysHandler
Specifies the Apple event dispatch table from which to get the handler. If isSysHandler is TRUE, the AEGetEventHandler function returns the handler from the system dispatch table. If isSysHandler is FALSE, AEGetEventHandler returns the handler from your application’s dispatch table.
DESCRIPTION
AEGetEventHandler returns a pointer in the handler parameter to the handler for the Apple event dispatch table entry you specify in the parameters theAEEventClass and theAEEventID. You can use the typeWildCard constant for either or both of these parameters; however, AEGetEventHandler will return an error unless an entry exists that specifies typeWildCard in exactly the same way. For example, if you specify typeWildCard in both the theAEEventClass parameter and the theAEEventID parameter, the Apple Event Manager will not return the first handler for any event class and event ID in the dispatch table; instead, the dispatch table must contain an entry that specifies type typeWildCard for both the event class and the event ID, or else AEGetEWventHandler will return an error.
RESULT CODES
noErr 0 No error
errAEHandlerNotFound –1717 No handler found for an Apple event
SEE ALSO
For an explanation of wildcard values, see the description of the AEInstallEventHandler function on page 2-184.
2AERemoveEventHandler
You can use the AERemoveEventHandler function to remove an entry from an Apple event dispatch table.
FUNCTION AERemoveEventHandler (theAEEventClass: AEEventClass;
theAEEventID: AEEventID;
handler: EventHandlerProcPtr;
isSysHandler: Boolean): OSErr;
theAEEventClass
The event class for the handler whose entry you want to remove from the Apple event dispatch table.
theAEEventID
The event ID for the handler whose entry you want to remove from the Apple event dispatch table.
handler A pointer to the Apple event handler to be removed. Although the parameters theAEEventClass and theAEEventID would be sufficient to identify the handler to be removed, providing the handler parameter is a safeguard that ensures that you remove the correct handler.
isSysHandler
Specifies the Apple event dispatch table from which to remove the handler. If isSysHandler is TRUE, AERemoveEventHandler removes the handler from the system dispatch table. If isSysHandler is FALSE, AERemoveEventHandler removes the handler from your application’s dispatch table.
DESCRIPTION
AERemoveEventHandler removes the Apple event dispatch table entry you specify in theparameters theAEEventClass, theAEEventID, and handler. You can use the typeWildCard constant for the theAEEventClass or the theAEEventID parameter, or for both parameters; however, AERemoveEventHandler will return an error unless an entry exists that specifies typeWildCard in exactly the same way. For example, if you specify typeWildCard in both the theAEEventClass parameter and the theAEEventID parameter, the Apple Event Manager will not remove the first handler for any event class and event ID in the dispatch table; instead, the dispatch table must contain an entry that specifies type typeWildCard for both the event class and the event ID, or else AERemoveEventHandler will return an error.
SEE ALSO
For an explanation of wildcard values, see the description of the AEInstallEventHandler function on page 2-184.
RESULT CODES
noErr 0 No error
errAEHandlerNotFound –1717 No handler found for an Apple event
Initializing the Object Support Library
You should call the AEObjectInit function to initialize the Apple Event Manager routines that handle object specifier records and Apple event objects. To make these routines available to your application, you must also link the Apple Event Object Support Library with your application when you build it.
2AEObjectInit
You use the AEObjectInit function to initialize the Object Support Library.
FUNCTION AEObjectInit : OSErr;
DESCRIPTION
You must call this function before calling any of the Apple Event Manager routines that describe or manipulate Apple event objects.
RESULT CODES
noErr 0 No error occurred
memFullErr –108 Not enough room in heap zone
errAENewerVersion –1706 Need a newer version of the Apple Event
Manager
Setting Object Accessor Functions and Object Callback Functions
The Apple Event Manager provides two routines that allow you to specify the object accessor functions and object callback functions provided by your application. The AEInstallObjectAccessor function adds an entry for an object accessor function to either the application’s object accessor dispatch table or the system object accessor dispatch table. The AESetObjectCallbacks function allows you to specify the object callback functions to be called for your application.
2AEInstallObjectAccessor
You can use the AEInstallObjectAccessor function to add an entry for an object accessor function to either the application’s object accessor dispatch table or the system object accessor dispatch table.
FUNCTION AEInstallObjectAccessor (desiredClass: DescType;
containerType: DescType;
theAccessor: AccessorProcPtr;
accessorRefcon: LongInt;
isSysHandler: Boolean): OSErr;
desiredClass
The object class of the Apple event objects that the object accessor function to be dispatched for this table entry can locate.
containerType
The descriptor type of the token used to specify the container for the desired objects. The object accessor function finds objects in containers specified by tokens of this type.
theAccessor
A pointer to the object accessor function for this table entry.
accessorRefcon
A reference constant passed by the Apple Event Manager to the object accessor function whenever the function is called. If your object accessor function doesn’t use a reference constant, use 0 as the value of this parameter.
isSysHandler
Specifies the object accessor dispatch table to which you add the object accessor function. If the value of isSysHandler is TRUE, the Apple Event Manager adds the routine to the system object accessor table. Entries in the system object accessor table are available to all applications running on the same computer. If the value of isSysHandler is FALSE, the Apple Event Manager adds the routine to your application’s object accessor table. The application accessor table is searched first; the system accessor table is searched only if the necessary function is not found in your application’s object accessor table.
DESCRIPTION
AEInstallObjectAccessor adds an entry to either the application or system object accessor table. You must supply parameters that specify the object class of the Apple event objects that the object accessor function can locate, the descriptor type of tokens for containers in which the object accessor function can locate objects, the address of the object accessor function for which you are adding an entry, and whether the entry is to be added to the system object accessor dispatch table or your application’s object accessor dispatch table. You can also specify a reference constant that the Apple Event Manager passes to your object accessor function each time the Apple Event Manager calls the function.
Note that an object accessor function in the system object accessor dispatch table must reside in the system heap; this means that if the value of the isSysHandler parameter is TRUE, the handler parameter must point to a location in the system heap.
RESULT CODES
noErr 0 No error occurred
paramErr –50 The handler pointer is NIL or odd, or
AEObjectInit was not called before this
function
SEE ALSO
For more information about installing object accessor functions, see “Installing Entries in the Object Accessor Dispatch Tables,” which begins on page 2-66.
2AESetObjectCallbacks
You can use the AESetObjectCallbacks function to specify the object callback functions to be called for your application.
FUNCTION AESetObjectCallbacks (myCompareProc,myCountProc,
myDisposeTokenProc,
myGetMarkTokenProc,myMarkProc,
myAdjustMarksProc,reserved:
ProcPtr): OSErr;
myCompareProc
Either a pointer to the object comparison function provided by your application or NIL if no function is provided.
myCountProc
Either a pointer to the object counting function provided by your application or NIL if no function is provided.
myDisposeTokenProc
Either a pointer to the token disposal function provided by your application or NIL if no function is provided.
myGetMarkTokenProc
Either a pointer to the function for returning a mark token provided by your application or NIL if no function is provided.
myMarkProc Either a pointer to the object marking function provided by your application or NIL if no function is provided.
myAdjustMarksProc
Either a pointer to the mark adjusting function provided by your application or NIL if no function is provided.
MyGetErrDescProc
Either a pointer to the error callback function provided by your application or NIL if no function is provided.
DESCRIPTION
Your application can provide only one each of the object callback functions specified by AESetObjectCallbacks: one comparison function, one counting function, and so on. As a result, each of these callback functions must perform the requested task (comparing, counting, and so on) for all the object classes that your application supports. In contrast, your application may provide many different object accessor functions if necessary, depending on the object classes and token types your application supports.
To replace object callback routines that have been previously installed, you can make another call to AESetObjectCallbacks. You can only do this to replace routines that can be installed by AESetObjectCallbacks; you cannot use AESetObjectCallbacks to replace system object callback routines or object accessor functions. Only those routines you specify are replaced; if you provide a value of NIL for any routine, the currently installed routine (if any) remains installed.
RESULT CODES
noErr 0 No error occurred
paramErr –50 The handler pointer is NIL or odd, or
AEObjectInit was not called before
this function
memFullErr –108 There is not enough room in heap zone
errAENotASpecialFunction –1714 The keyword is not a valid keyword for a
special function
SEE ALSO
For examples of object callback functions that your application might provide, see “Application-Defined Functions,” which begins on page 2-254.
To install system object callback functions, use the AEInstallSpecialHandler function described on page 2-251.
Getting, Calling, and Removing Object Accessor Functions
The Apple Event Manager provides three routines that allow you to get, call, and remove object accessor functions that you have installed in either the system or application object accessor dispatch table with the AEInstallObjectAccessor function. The AEGetObjectAccessor function allows you to get a pointer to an object accessor function and the value of its reference constant. The AECallObjectAccessor function allows you to invoke one of your object accessor functions. The AERemoveObjectAccessor function allows you to remove an object accessor function from an object accessor dispatch table.
2AEGetObjectAccessor
You can use the AEGetObjectAccessor function to get a pointer to an object accessor function and the value of its reference constant.
FUNCTION AEGetObjectAccessor (desiredClass: DescType;
containerType: DescType;
VAR theAccessor: AccessorProcPtr;
VAR accessorRefcon: LongInt;
isSysHandler: Boolean): OSErr;
desiredClass
The object class of the Apple event objects located by the requested object accessor function. This parameter can also contain the constant typeWildCard or the constant cProperty.
containerType
The descriptor type of the token that identifies the container for the Apple event objects located by the requested object accessor function. This parameter can also contain the constant typeWildCard.
theAccessor
The AEGetObjectAccessor function returns a pointer to the requested object accessor function in this parameter.
accessorRefcon
The AEGetObjectAccessor function returns the reference constant from the object accessor dispatch table entry for the specified object accessor function in this parameter.
isSysHandler
Specifies the object accessor table from which to get the object accessor function and its reference constant. If isSysHandler is TRUE, AEGetObjectAccessor gets the function from the system object accessor dispatch table. If isSysHandler is FALSE, AEGetObjectAccessor gets the function from the application’s object accessor dispatch table.
DESCRIPTION
AEGetObjectAccessor returns a pointer to the object accessor function installed for the object class specified in the desiredClass parameter and the descriptor type specified in the containerType parameter. AEGetObjectAccessor also returns the reference constant associated with the specified function. You must supply a value in the isSysHandler parameter that specifies which object accessor dispatch table you want to get the function from.
Calling AEGetObjectAccessor does not remove the object accessor function from an object accessor dispatch table.
To get an object accessor function whose entry in an object accessor dispatch table specifies typeWildCard as the object class, you must specify typeWildCard as the value of the desiredClass parameter. Similarly, to get an object accessor function whose entry in an object accessor dispatch table specifies typeWildCard as the descriptor type of the token used to specify the container for the desired objects, you must specify typeWildCard as the value of the containerType parameter.
To get an object accessor function whose entry in an object accessor dispatch table specifies cProperty (a constant used to specify a property of any object class), you must specify cProperty as the desiredClass parameter.
RESULT CODES
noErr 0 No error occurred
paramErr –50 AEObjectInit was not called before
this function was called
errAEAccessorNotFound –1723 There is no object accessor function for
the specified object class and container
type
2AECallObjectAccessor
You can use the AECallObjectAccessor function to invoke one of your application’s object accessor functions.
FUNCTION AECallObjectAccessor (desiredClass: DescType;
containerToken: AEDesc;
containerClass: DescType;
keyForm: DescType;
keyData: AEDesc;
VAR theToken: AEDesc): OSErr;
desiredClass
The object class of the requested Apple event objects.
containerToken
The token that identifies the container for the desired Apple event objects.
containerClass
The object class of the container for the desired Apple event objects.
keyForm The key form specified by the object specifier record for the object or objects to be located.
keyData The key data specified by the object specifier record for the object or objects to be located.
theToken The object accessor function that is invoked returns a token specifying the desired object or objects in this parameter.
DESCRIPTION
If you want your application to do some of the Apple event object resolution normally performed by the AEResolve function, you can use AECallObjectAccessor to invoke an object accessor function. This might be useful, for example, when you have installed an object accessor function in an object accessor dispatch table by specifying the constant typeWildCard for the AEInstallObjectAccessor function’s desiredClass parameter, containerType parameter, or both parameters. Your application can take care of some initial processing that is the same for all incoming requests and then call AEResolve to do the rest.
The parameters of AECallObjectAccessor are identical to the parameters of an object accessor function, with one exception: the parameter that specifies the reference constant passed to the object accessor function whenever it is called is added by the Apple Event Manager when it calls the object accessor function.
To call an object accessor function whose entry in an object accessor dispatch table specifies typeWildCard as the object class, you must specify typeWildCard as the value of the desiredClass parameter.
To call an object accessor function whose entry in an object accessor dispatch table specifies cProperty, you must specify cProperty as the desiredClass parameter.
RESULT CODES
In addition to the following result codes, AECallObjectAccessor returns any other result codes returned by the object accessor function that is called.
noErr 0 No error occurred.
paramErr –50 AEObjectInit was not called before
calling this function.
errAEEventNotHandled –1708 No object accessor was found.
2AERemoveObjectAccessor
You can use the AERemoveObjectAccessor function to remove an object accessor function from an object accessor dispatch table.
FUNCTION AERemoveObjectAccessor (desiredClass: DescType;
containerType: DescType;
theAccessor: AccessorProcPtr;
isSysHandler: Boolean): OSErr;
desiredClass
The object class of the Apple event objects located by the object accessor function. The desiredClass parameter can also contain the constant typeWildCard or the constant cProperty.
containerType
The descriptor type of the token that identifies the container for the Apple event objects located by the object accessor function. The containerType can also contain the constant typeWildCard.
theAccessor
A pointer to the object accessor function you want to remove. Although the parameters desiredClass and containerClass would be sufficient to identify the function to be removed, providing the parameter theAccessor guarantees that you remove the correct function. If this parameter does not contain a pointer to the object accessor function you want to remove, its value should be NIL.
isSysHandler
Specifies the object accessor dispatch table from which to delete the object accessor function. If isSysHandler is TRUE, AEGetObjectAccessor removes the routine from the system object accessor dispatch table. If isSysHandler is FALSE, AEGetObjectAccessor removes the routine from the application object accessor dispatch table.
DESCRIPTION
AERemoveObjectAccessor removes the object accessor function you have installed for the object class specified in the desiredClass parameter and the descriptor type specified in the containerType parameter.
To remove an object accessor function whose entry in an object accessor dispatch table specifies typeWildCard as the object class, you must specify typeWildCard as the value of the desiredClass parameter. Similarly, to remove an object accessor function whose entry in an object accessor dispatch table specifies typeWildCard as the descriptor type of the token used to specify the container for the desired objects, you must specify typeWildCard as the value of the containerType parameter.
To remove an object accessor function whose entry in an object accessor dispatch table specifies cProperty (a constant used to specify a property of any object class), you must specify cProperty as the desiredClass parameter.
RESULT CODES
noErr 0 No error occurred.
paramErr –50 AEObjectInit was not called before
calling this function.
errAEAccessorNotFound –1723 There is no object accessor function for
the specified object class and container
type.
Dispatching Apple Events
After receiving a high-level event (and optionally determining whether it is a type of high-level event other than an Apple event that your application might support), your application typically calls the AEProcessAppleEvent function to determine the type of Apple event received and call the corresponding handler.
2AEProcessAppleEvent
You can use the AEProcessAppleEvent function to call the appropriate handler in your application for a specified Apple event.
FUNCTION AEProcessAppleEvent
(theEventRecord: EventRecord): OSErr;
theEventRecord
The event record for the Apple event.
DESCRIPTION
The AEProcessAppleEvent function looks first in the application’s special handler dispatch table for an entry that was installed with the constant keyPreDispatch. If the application’s special handler dispatch table does not include such a handler or if the handler returns errAEEventNotHandled, the function looks in the application’s Apple event dispatch table for an entry that matches the event class and event ID of the specified Apple event.
If the application’s Apple event dispatch table does not include such a handler or if the handler returns errAEEventNotHandled, the AEProcessAppleEvent function looks in the system special handler dispatch table for an entry that was installed with the constant keyPreDispatch. If the system special handler dispatch table does not include such a handler or if the handler returns errAEEventNotHandled, the function looks in the system Apple event dispatch table for an entry that matches the event class and event ID of the specified Apple event.
If the system special handler dispatch table does not include such a handler, the Apple Event Manager returns the result code errAEEventNotHandled to the server application and, if the client application is waiting for a reply, to the client application.
If an Apple dispatch table contains one entry for an event class and a specific event ID, and also contains another entry that is identical except that it specifies a wildcard value for either the event class or the event ID, the Apple Event Manager will dispatch the more specific entry. For example, if an Apple event dispatch table includes one entry that specifies the event class as kAECoreSuite and the event ID as kAEDelete, and another entry that specifies the event class as kAECoreSuite and the event ID as typeWildCard, the Apple Event Manager will dispatch the Apple event handler associated with the entry that specifies the event ID as kAEDelete.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
bufferIsSmall –607 Buffer is too small
noOutstandingHLE –608 No outstanding high-level event
errAECorruptData –1702 Data in an Apple event could not be read
errAENewerVersion –1706 Need a newer version of the Apple Event
Manager
errAEEventNotHandled –1708 Event wasn’t handled by an Apple event
handler
Getting Data or Descriptor Records from Apple Event Parameters and Attributes
The Apple Event Manager provides four functions that allow you to get data from Apple event parameters and attributes. The AEGetParamPtr and AEGetParamDesc functions get data from a specified Apple event parameter. The AEGetAttributePtr and AEGetAttributeDesc functions get data from a specified Apple event attribute.
2AEGetParamPtr
You can use the AEGetParamPtr function to get a pointer to a buffer that contains the data from a specified Apple event parameter.
FUNCTION AEGetParamPtr (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword;
desiredType: DescType;
VAR typeCode: DescType; dataPtr: Ptr;
maximumSize: Size;
VAR actualSize: Size): OSErr;
theAppleEvent
The Apple event containing the desired parameter.
theAEKeyword
The keyword that specifies the desired parameter.
desiredType
The desired descriptor type for the data to be returned; if the requested Apple event parameter is not of this type, the Apple Event Manager attempts to coerce it to this type. If the value of desiredType is typeWildCard, no coercion is performed, and the descriptor type of the returned data is the same as the descriptor type of the Apple event parameter.
typeCode The descriptor type of the returned data.
dataPtr A pointer to the buffer in which the returned data is stored.
maximumSize
The maximum length, in bytes, of the data to be returned. You must allocate at least this amount of storage for the buffer specified by the dataPtr parameter.
actualSize The length, in bytes, of the data for the specified Apple event parameter. If this value is larger than the value of the maximumSize parameter, not all of the data for the parameter was returned.
DESCRIPTION
The AEGetParamPtr function uses a buffer to return the data from a specified Apple event parameter, which it attempts to coerce to the descriptor type specified by the desiredType parameter.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the
requested descriptor type
errAEDescNotFound –1701 Descriptor record was not found
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
2AEGetParamDesc
You can use the AEGetParamDesc function to get the descriptor record for a specified Apple event parameter.
FUNCTION AEGetParamDesc (theAppleEvent: AppleEvent; theAEKeyword:
AEKeyword; desiredType: DescType;
VAR result: AEDesc): OSErr;
theAppleEvent
The Apple event containing the desired parameter.
theAEKeyword
The keyword that specifies the desired parameter.
desiredType
The desired descriptor type for the descriptor record to be returned; if the requested Apple event parameter is not of this type, the Apple Event Manager attempts to coerce it to this type. If the value of desiredType is typeWildCard, no coercion is performed, and the descriptor type of the returned data is the same as the descriptor type of the Apple event parameter.
result The descriptor record from the desired Apple event parameter coerced to the descriptor type specified in desiredType.
DESCRIPTION
The AEGetParamDesc function returns the descriptor record for a specified Apple event parameter, which it attempts to coerce to the descriptor type specified by the desiredType parameter. Your application should call the AEDisposeDesc function to dispose of the resulting descriptor record after your application has finished using it.
If AEGetParamDesc returns a nonzero result code, it returns a null descriptor record (a descriptor record of type typeNull, which does not contain any data) unless the Apple Event Manager is not available due to limited memory.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested
descriptor type
errAEDescNotFound –1701 Descriptor type was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
2AEGetAttributePtr
You can use the AEGetAttributePtr function to get a pointer to a buffer that contains the data from a specified Apple event attribute.
FUNCTION AEGetAttributePtr (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword;
desiredType: DescType;
VAR typeCode: DescType; dataPtr: Ptr;
maximumSize: Size;
VAR actualSize: Size): OSErr;
theAppleEvent
The Apple event containing the desired attribute.
theAEKeyword
The keyword that specifies the desired attribute.
desiredType
The desired descriptor type for the data to be returned; if the requested Apple event attribute is not of this type, the Apple Event Manager attempts to coerce it to this type. If the value of desiredType is typeWildCard, no coercion is performed, and the descriptor type of the returned data is the same as the descriptor type of the Apple event attribute.
typeCode The descriptor type of the returned data.
dataPtr A pointer to the buffer in which the returned data is stored.
maximumSize
The maximum length, in bytes, of the data to be returned. You must allocate at least this amount of storage for the buffer specified by the dataPtr parameter.
actualSize The length, in bytes, of the data for the specified Apple event attribute. If this value is larger than the value of the maximumSize parameter, not all of the data for the attribute was returned.
DESCRIPTION
The AEGetAttributePtr function uses a buffer to return the data from an Apple event attribute with the specified keyword, which it attempts to coerce to the descriptor type specified by the desiredType parameter. The keyword can be one of the following:
Attribute keyword Value Description
keyAddressAttr 'addr' Address of target application
keyEventClassAttr 'evcl' Event class of Apple event
keyEventIDAttr 'evid' Event ID of Apple event
keyEventSourceAttr 'esrc' Source of the Apple event
keyInteractLevelAttr 'inte' Settings for allowing the Apple Event
Manager to bring a server application
to the foreground
keyMissedKeywordAttr 'miss' First required parameter remaining in
an Apple event
keyOptionalKeywordAttr 'optk' List of optional parameters
for the Apple event
keyReturnIDAttr 'rtid' Return ID for reply Apple event
keyTimeoutAttr 'timo' Length of time in ticks that the client
will wait for a reply or a result from
the server
keyTransactionIDAttr 'tran' Transaction ID identifying a series of
Apple events
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested
descriptor type
errAEDescNotFound –1701 Descriptor type was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
2AEGetAttributeDesc
You can use the AEGetAttributeDesc function to get the descriptor record for a specified Apple event attribute.
FUNCTION AEGetAttributeDesc (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword;
desiredType: DescType;
VAR result: AEDesc): OSErr;
theAppleEvent
The Apple event containing the desired attribute.
theAEKeyword
The keyword that specifies the desired parameter.
desiredType
The desired descriptor type for the descriptor record to be returned; if the requested Apple event attribute is not of this type, the Apple Event Manager attempts to coerce it to this type. If the value of desiredType is typeWildCard, no coercion is performed, and the descriptor type of the returned data is the same as the descriptor type of the Apple event attribute.
result A copy of the descriptor record from the desired attribute coerced to the descriptor type specified by the desiredType parameter.
DESCRIPTION
The AEGetAttributeDesc function returns the descriptor record for the Apple event attribute with the specified keyword . Your application should call the AEDisposeDesc function to dispose of the resulting descriptor record after your application has finished using it.
The keyword can be one of the following:
Attribute keyword Value Description
keyAddressAttr 'addr' Address of target application
keyEventClassAttr 'evcl' Event class of Apple event
keyEventIDAttr 'evid' Event ID of Apple event
keyEventSourceAttr 'esrc' Source of the Apple event
keyInteractLevelAttr 'inte' Settings for allowing the Apple Event
Manager to bring a server application
to the foreground
keyMissedKeywordAttr 'miss' First required parameter remaining in
an Apple event
keyOptionalKeywordAttr 'optk' List of optional parameters
for the Apple event
keyReturnIDAttr 'rtid' Return ID for reply Apple event
keyTimeoutAttr 'timo' Length of time in ticks that the client
will wait for a reply or a result from
the server
keyTransactionIDAttr 'tran' Transaction ID identifying a series of
Apple events
If AEGetAttributeDesc returns a nonzero result code, it returns a null descriptor record (a descriptor record of type typeNull, which does not contain any data) unless the Apple Event Manager is not available due to limited memory.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested
descriptor type
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
Counting the Items in Descriptor Lists
The AECountItems function counts the number of descriptor records in any descriptor list, including an Apple event record.
2AECountItems
You can use the AECountItems function to count the number of descriptor records in any descriptor list.
FUNCTION AECountItems (theAEDescList: AEDescList;
VAR theCount: LongInt): OSErr;
theAEDescList
The descriptor list to be counted.
theCount The number of descriptor records in the specified descriptor list.
RESULT CODES
noErr 0 No error
errAENotAEDesc –1704 Not a valid descriptor record
Getting Items From Descriptor Lists
The Apple Event Manager provides three functions that allow you to get items from any descriptor list, including an Apple event record. The AEGetNthPtr and AEGetNthDesc functions give you access to the data in a descriptor list. The AEGetArray function gets data from an array contained in a descriptor list.
2AEGetNthPtr
You can use the AEGetNthPtr function to get a pointer to a buffer that contains a descriptor record from any descriptor list.
FUNCTION AEGetNthPtr (theAEDescList: AEDescList; index: LongInt;
desiredType: DescType; VAR theAEKeyword:
AEKeyword; VAR typeCode: DescType;
dataPtr: Ptr; maximumSize: Size;
VAR actualSize: Size): OSErr;
theAEDescList
The descriptor list containing the desired descriptor record.
index The position of the desired descriptor record in the list (for example, 2 specifies the second descriptor record).
desiredType
The desired descriptor type of the copy of the descriptor record; if the desired descriptor record is not of this type, the Apple Event Manager attempts to coerce it to this type. If the value of desiredType is typeWildCard, no coercion is performed, and the descriptor type of the copied descriptor record is the same as the descriptor type of the original descriptor record.
theAEKeyword
The keyword of the specified descriptor record, if you are getting data from a list of keyword-specified descriptor records; otherwise, AEGetNthPtr returns the value typeWildCard.
typeCode The descriptor type of the returned descriptor record.
dataPtr A pointer to the buffer in which the returned descriptor record is stored.
maximumSize
The maximum length, in bytes, of the data to be returned. You must allocate at least this amount of storage for the buffer specified by the dataPtr parameter.
actualSize The length, in bytes, of the data for the specified descriptor record. If this value is larger than the value of the maximumSize parameter, not all of the data for the descriptor record was returned.
DESCRIPTION
The AEGetNthPtr function uses a buffer to return a specified descriptor record from a specified descriptor list; the function attempts to coerce the descriptor record to the descriptor type specified by the desiredType parameter.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested
descriptor type
errAEDescNotFound –1701 Descriptor record was not found
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
2AEGetNthDesc
You can use the AEGetNthDesc function to get a descriptor record from any descriptor list.
FUNCTION AEGetNthDesc (theAEDescList: AEDescList; index: LongInt;
desiredType: DescType; VAR theAEKeyword:
AEKeyword; VAR result: AEDesc): OSErr;
theAEDescList
The descriptor list containing the desired descriptor record.
index The position of the desired descriptor record in the list (for example, 2 specifies the second descriptor record).
desiredType
The desired descriptor type for the copy of the descriptor record to be returned; if the desired descriptor record is not of this type, the Apple Event Manager attempts to coerce it to this type. If the value of desiredType is typeWildCard, no coercion is performed, and the descriptor type of the returned descriptor record is the same as the descriptor type of the original descriptor record.
theAEKeyword
The keyword of the specified descriptor record, if you are getting data from a list of keyword-specified descriptor records; otherwise, AEGetNthDesc returns the value typeWildCard.
result A copy of the desired descriptor record coerced to the descriptor type specified by the desiredType parameter.
DESCRIPTION
The AEGetNthDesc function returns a specified descriptor record from a specified descriptor list.Your application should call the AEDisposeDesc function to dispose of the resulting descriptor record after your application has finished using it.
If AEGetNthDesc returns a nonzero result code, it returns a descriptor record of descriptor type typeNull. A descriptor record of this type does not contain any data.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested
descriptor type
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
2AEGetArray
You can use the AEGetArray function to convert an Apple event array (an array created with the AEPutArray function and stored in a descriptor list) into the corresponding Pascal or C array.
FUNCTION AEGetArray (theAEDescList: AEDescList;
arrayType: AEArrayType;
arrayPtr: AEArrayDataPointer;
maximumSize: Size;
VAR itemType: DescType; VAR itemSize: Size;
VAR itemCount: LongInt): OSErr;
theAEDescList
A factored descriptor list containing the desired array.
arrayType The Apple event array type to be converted. This is specified by one of the following constants: kAEDataArray, kAEPackedArray, kAEHandleArray, kAEDescArray, or kAEKeyDescArray.
arrayPtr A pointer to the buffer for storing the array.
maximumSize
The maximum length, in bytes, of the buffer for storing the array.
itemType For packed, data, and handle arrays, the AEGetArray function returns the descriptor type of the returned array items in this parameter.
itemSize For packed and data arrays, the AEGetArray function returns the size, in bytes, of the returned array items in this parameter.
itemCount The AEGetArray function returns the number of items in the resulting array in this parameter.
DESCRIPTION
The AEGetArray function converts the Apple event array specified by the theAEDescList parameter into the corresponding Pascal or C array.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
Getting Data and Keyword-Specified Descriptor Records From AE Records
The AEGetKeyPtr and AEGetKeyDesc functions allow you to get data and keyword-specified descriptor records out of an AE record or an Apple event record.
2AEGetKeyPtr
You can use the AEGetKeyPtr function to get a pointer to a buffer that contains the data from a keyword-specified descriptor record. You can use this function to get data out of an AE record or an Apple event record.
FUNCTION AEGetKeyPtr (theAERecord: AERecord; theAEKeyword:
AEKeyword; desiredType: DescType;
VAR typeCode: DescType;
dataPtr: Ptr; maximumSize: Size;
VAR actualSize: Size): OSErr;
theAERecord
The AE record containing the desired data.
theAEKeyword
The keyword that specifies the desired descriptor record.
desiredType
The desired descriptor type for the data to be returned; if the requested data is not of this type, the Apple Event Manager attempts to coerce it to this type. If the value of desiredType is typeWildCard, no coercion is performed, and the descriptor type of returned data is the same as the descriptor type of the original data.
typeCode The descriptor type of the returned data.
dataPtr A pointer to the buffer for storing the data.
maximumSize
The maximum length, in bytes, of the data to be returned. You must allocate at least this amount of storage for the buffer specified by the dataPtr parameter.
actualSize The length, in bytes, of the data for the keyword-specified descriptor record. If this value is larger than the value of the maximumSize parameter, not all of the data for the parameter was returned.
DESCRIPTION
The AEGetKeyPtr function uses a buffer to return the data from a keyword-specified Apple event parameter, which it attempts to coerce to the descriptor type specified by the desiredType parameter.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested
descriptor type
errAEDescNotFound –1701 Descriptor record was not found
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
2AEGetKeyDesc
You can use the AEGetKeyDesc function to get the descriptor record for a keyword-specified descriptor record. You can use this function to get a descriptor record out of an AE record or an Apple event record.
FUNCTION AEGetKeyDesc (theAERecord: AERecord;
theAEKeyword: AEKeyword;
desiredType: DescType;
VAR result: AEDesc): OSErr;
theAERecord
The AE record containing the desired descriptor record.
theAEKeyword
The keyword that specifies the desired descriptor record.
desiredType
The desired descriptor type for the descriptor record to be returned; if the requested descriptor record is not of this type, the Apple Event Manager attempts to coerce it into this type. If the value of desiredType is typeWildCard, no coercion is performed, and the descriptor type of the returned descriptor record is the same as the descriptor type of the original descriptor record.
result A copy of the keyword-specified descriptor record, coerced to the descriptor type specified in the desiredType parameter.
DESCRIPTION
The AEGetKeyDesc function returns a copy of the descriptor record for a keyword-specified descriptor record. Your application should call the AEDisposeDesc function to dispose of the resulting descriptor record after your application has finished using it.
If AEGetKeyDesc returns a nonzero result code, it returns a descriptor record of descriptor type typeNull. A descriptor record of this type does not contain any data.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested
descriptor type
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
Resolving Object Specifier Records
If an Apple event parameter consists of an object specifier record, your handler for the event typically calls the AEResolve function to begin the process of resolving the object specifier record.
2AEResolve
You can use the AEResolve function to resolve an object specifier record in an Apple event parameter.
FUNCTION AEResolve (objectSpecifier: AEDesc;
callbackFlags: Integer;
VAR theToken: AEDesc): OSErr;
objectSpecifier
The object specifier record to be resolved.
callbackFlags
A value that determines what additional assistance, if any, your application can give the Apple Event Manager when it parses the object specifier record. The value is specified by adding the following constants, as appropriate:
CONST kAEIDoMinimum = $0000 ; {Supports minimum }
{ callbacks only}
kAEIDoWhose = $0001 ; {Supports formWhose}
kAEIDoMarking = $0004 ; {Provides marking }
{ functions}
theToken A token that identifies the Apple event object specified by the objectSpecifier parameter. Your object accessor functions may need to create many tokens in order to resolve a single object specifier record; this parameter contains only the final token that identifies the requested Apple event object. If an error occurs, AEResolve returns a null descriptor record.
DESCRIPTION
The AEResolve function resolves the object specifier record passed in the objectSpecifier parameter with the help of the object accessor functions and object callback functions provided by your application.
RESULT CODES
noErr 0 No error occurred
paramErr –50 AEObjectInit was not called before
this function was called
errAEHandlerNotFound –1717 The necessary object callback function
was not found (this result is returned only
forobject callback functions;
errAEAccessorNotFound [–1723] is
returned when an object accessor function
is not found)
errAEImpossibleRange –1720 The range is not valid because it is
impossible for a range to include the first
and last objects that were specified; an
example is a range in which the offset of
the first object is greater than the offset of
the last object
errAEWrongNumberArgs –1721 The number of operands provided for
the kAENot logical operator is not 1
errAEAccessorNotFound –1723 There is no object accessor function for
the specified object class and token
descriptor type
errAENoSuchLogical –1725 The logical operator in a logical
descriptor is not kAEAnd, kAEOr, or kAENot
errAEBadTestKey –1726 The descriptor in a test key is neither a
comparison descriptor record nor a logical
descriptor record
errAENotAnObjectSpec –1727 The objSpecifier parameter of
AEResolve is not an object specifier
record
errAEnegativeCount –1729 An object-counting function returned a
negative result
errAEemptyListContainer –1730 The container specified for an Apple
event object is an empty list
In addition to the result codes listed here, AEResolve also returns any result code returned by one of your application’s object accesssor functions or object callback functions. For example, an object accessor function can return errAENoSuchObject (–1728) when it can’t find an Apple event object, or it can return more specific result codes.
If any object accessor function or object callback function returns a result code other than noErr or errAEEventNotHandled, AEResolve immediately disposes of any existing tokens and returns. The result code it returns in this case is the result code returned by the object accessor function or the object callback function.
SEE ALSO
For an overview of the way AEResolve works with objects accessor functions, see “Resolving Object Specifier Records,” which begins on page 2-53
Requesting User Interaction
The Apple Event Manager provides three functions that allow you to set or request user interaction levels and to initiate user interaction when your application is the server application. The AESetInteractionAllowed and AEGetInteractionAllowed functions specify the user interaction preferences for your application. Your application should call the AEInteractWithUser function before actually interacting with the user in response to an Apple event.
2AESetInteractionAllowed
You can use the AESetInteractionAllowed function to specify your application’s user interaction preferences for responding to an Apple event.
FUNCTION AESetInteractionAllowed
(level: AEInteractAllowed): OSErr;
level The user interaction level to be set.
DESCRIPTION
AESetInteractionAllowed sets the user interaction level for a server application’s response to an Apple event. The level parameter must be one of three flags: kAEInteractWithSelf, kAEInteractWithLocal, or kAEInteractWithAll.
Specifying the kAEInteractWithSelf flag allows the server application to interact with the user in response to an Apple event only when the client application and server application are the same—that is, only when the application is sending the Apple event to itself.
Specifying the kAEInteractWithLocal flag allows the server application to interact with the user in response to an Apple event only if the client application is on the same computer as the server application; this is the default if the AESetInteractionAllowed function is not used.
Specifying the kAEInteractWithAll flag allows the server application to interact with the user in response to an Apple event sent from any client application on any computer.
RESULT CODE
noErr 0 No error
2AEGetInteractionAllowed
You can use the AEGetInteractionAllowed function to get the current user interaction preferences for responding to an Apple event.
FUNCTION AEGetInteractionAllowed
(VAR level: AEInteractAllowed): OSErr;
level The current user interaction level, using the data type AEInteractAllowed:
TYPE AEInteractAllowed = (kAEInteractWithSelf,
kAEInteractWithLocal,
kAEInteractWithAll);
DESCRIPTION
The AEGetInteractionAllowed function returns a value in the level parameter that indicates the user interaction preferences for responding to an Apple event. The value returned is the interaction level set by a previous call to AESetInteractionAllowed, and consists of one of the following flags: kAEInteractWithSelf, kAEInteractWithLocal, or kAEInteractWithAll. The default value of kAEInteractWithLocal is returned if your application has not used AESetInteractionAllowed to set the interaction level explicitly.
The kAEInteractWithSelf flag indicates that the server application may interact with the user in response to an Apple event only when the client application and server application are the same—that is, only when the application is sending the Apple event to itself.
The kAEInteractWithLocal flag indicates that the server application may interact with the user in response to an Apple event only if the client application is on the same computer as the server application. This is the default if your application has not used the AESetInteractionAllowed function to set the interaction level explicitly.
The kAEInteractWithAll flag indicates that the server application may interact with the user in response to an Apple event sent from any client application on any computer.
RESULT CODE
noErr 0 No error
2AEInteractWithUser
You can use the AEInteractWithUser function to initiate interaction with the user when your application is a server application responding to an Apple event.
FUNCTION AEInteractWithUser
(timeOutInTicks: LongInt; nmReqPtr:
NMRecPtr; idleProc: IdleProcPtr): OSErr;
timeOutInTicks
The amount of time (in ticks) that your handler is willing to wait for a response from the user. You can specify a number of ticks or use one of the following constants:
CONST kAEDefaultTimeout = -1; {value determined }
{ by AEM}
kNoTimeOut = -2; {wait until reply }
{ comes back}
nmReqPtr A pointer to a Notification Manager record provided by your application. You can specify NIL for this parameter to get the default notification handling provided by the Apple Event Manager.
idleProc A pointer to your application’s idle function, which handles events while waiting for the Apple Event Manager to return control.
DESCRIPTION
Your application should call the AEInteractWithUser function before displaying a dialog box or alert box or otherwise interacting with the user in response to an Apple event. If the user interaction preference settings permit the application to come to the foreground, this function brings your application to the front, either directly or by posting a notification request.
The AEInteractWithUser function checks to see if the client application set the kAENeverInteract flag for the Apple event and, if so, returns an error. If not, then the AEInteractWithUser function checks the server application’s preference set by the AESetInteractionAllowed function and compares it against the source of the Apple event—that is, whether it came from the same application, another process on the same computer, or a process running on another computer. AEInteractWithUser returns the errAENoUserInteraction result code if the user interaction preferences don’t allow user interaction. If user interaction is allowed, the Apple Event Manager brings your application to the front, either directly or by posting a notification request. If AEInteractWithUser returns the noErr result code, then your application is in the foreground and is free to interact with the user.
RESULT CODES
noErr 0 No error
errAETimeout –1712 Apple event timed out
errAENoUserInteraction –1713 No user interaction allowed
SEE ALSO
For a description of how to write an idle function, see “Writing an Idle Function” on page 2-150.
For examples of the use of the AEInteractWithUser function, see “Interacting With the User,” which begins on page 2-100.
Requesting More Time to Respond to Apple Events
The AEResetTimer function resets the timeout value for an Apple event to its starting value. A server application can call this function when it knows it cannot fulfill a client application’s request (either by returning a result or by sending back a reply Apple event) before the client application is due to time out.
2AEResetTimer
You can use the AEResetTimer function to reset the timeout value for an Apple event to its starting value.
FUNCTION AEResetTimer (reply: AppleEvent): OSErr;
reply The default reply for an Apple event, provided by the Apple Event Manager.
DESCRIPTION
When your application calls AEResetTimer, the Apple Event Manager for the server application uses the default reply to send a Reset Timer event to the client application; the Apple Event Manager for the client application intercepts this Apple event and resets the client application’s timer for the Apple event. (The Reset Timer event is never dispatched to a handler, so the client application does not need a handler for it.)
RESULT CODES
noErr 0 No error
errAEReplyNotValid –1709 AEResetTimer was passed an invalid reply
Suspending and Resuming Apple Event Handling
The Apple Event Manager provides four functions that allow you to suspend and resume Apple event handling, specify the Apple event to be handled, and identify an Apple event that is currently being handled. The AESuspendTheCurrentEvent function allows you to suspend the processing of the Apple event that is currently being handled. The AEResumeTheCurrentEvent function informs the Apple Event Manager that your application wants to resume the handling of a previously suspended Apple event or that it has completed the handling of the Apple event. The AESetTheCurrentEvent function specifies the Apple event to be handled. The AEGetTheCurrentEvent function returns the Apple event that is currently being handled.
2AESuspendTheCurrentEvent
You can use the AESuspendTheCurrentEvent function to suspend the processing of the Apple event that is currently being handled.
FUNCTION AESuspendTheCurrentEvent
(theAppleEvent: AppleEvent): OSErr;
theAppleEvent
The Apple event whose handling is to be suspended. Although the Apple Event Manager doesn’t need this parameter to identify the Apple event currently being handled, providing it is a safeguard that ensures that you are suspending the correct Apple event.
DESCRIPTION
After a server application makes a successful call to the AESuspendTheCurrentEvent function, it is no longer required to return a result or a reply for the Apple event that was being handled. It can, however, return a result if it later calls the AEResumeTheCurrentEvent function to resume event processing.
The Apple Event Manager does not automatically dispose of Apple events that have been suspended or of their default replies. (The Apple Event Manager does, however, automatically dispose of a previously suspended Apple event and its default reply if the server later resumes processing of the Apple event by calling the AEResumeTheCurrentEvent function.) If your server application does not resume processing of a suspended Apple event, it is responsible for using the AEDisposeDesc function to dispose of both the Apple event and its default reply when your application is finished with them.
RESULT CODES
noErr 0 No error
2AEResumeTheCurrentEvent
You can use the AEResumeTheCurrentEvent function to inform the Apple Event Manager that your application wants to resume the handling of a previously suspended Apple event or that it has completed the handling of the Apple event.
FUNCTION AEResumeTheCurrentEvent
(theAppleEvent,reply: AppleEvent;
dispatcher: EventHandlerProcPtr;
handlerRefcon: LongInt): OSErr;
theAppleEvent
The Apple event whose processing is to be resumed.
reply The default reply that is automatically provided by the Apple Event Manager for the Apple event.
dispatcher One of the following:
n a pointer to a routine for handling the event
n the kAEUseStandardDispatch constant, which causes the Apple event to be dispatched the same way it was when it was first received
n the kAENoDispatch constant, which tells the Apple Event Manager that the processing of the Apple event is complete and that it does not need to be dispatched
handlerRefcon
If the value of the dispatcher parameter is not kAEUseStandardDispatch, this parameter is the reference constant that is passed to the handler when the handler is called. If the value of the dispatcher parameter is kAEUseStandardDispatch, the Apple Event Manager ignores the handlerRefcon parameter and instead passes the reference constant that is stored in the Apple event dispatch table entry for the Apple event. (If you want to pass the same reference constant that is stored in the Apple event dispatch table, your application can obtain the reference constant by calling the AEGetEventHandler function.)
DESCRIPTION
When your application calls the AEResumeTheCurrentEvent function, the Apple Event Manager resumes the handling of the specified Apple event using the handler specified in the dispatcher parameter; if kAENoDispatch is specified, this function simply informs the Apple Event Manager that the specified event has been handled.
RESULT CODE
noErr 0 No error
2AESetTheCurrentEvent
You can use the AESetTheCurrentEvent function to specify the Apple event to be handled.
FUNCTION AESetTheCurrentEvent (theAppleEvent: AppleEvent):
OSErr;
theAppleEvent
The Apple eventto be handled.
DESCRIPTION
There is usually no reason for your application to use the AESetTheCurrentEvent function. Instead of calling this function, your application should let the Apple Event Manager set the current Apple event through the dispatch tables.
If you need to avoid the dispatch tables, you must use the AESetTheCurrentEvent function only in the following way:
1. Your application suspends handling of an Apple event by calling the AESuspendTheCurrentEvent function.
2. Your application calls the AESetTheCurrentEvent function to inform the Apple Event Manager that it is handling the Apple event that was suspended. It thereby makes the identity of the Apple event currently being handled available to routines that call the AEGetTheCurrentEvent function.
3. When your application finishes handling the Apple event, it calls the AEResumeTheCurrentEvent function with the value kAENoDispatch to tell the Apple Event Manager that the processing of the event is complete and that the Apple event does not need to be dispatched.
RESULT CODE
noErr 0 No error
2AEGetTheCurrentEvent
You can use the AEGetTheCurrentEvent function to get the Apple event that is currently being handled.
FUNCTION AEGetTheCurrentEvent
(VAR theAppleEvent: AppleEvent): OSErr;
theAppleEvent
The Apple event that is currently being handled; if no Apple event is currently being handled, AEGetTheCurrentEvent returns a null descriptor record in this parameter
DESCRIPTION
In many applications, the handling of an Apple event involves one or more long chains of calls to routines within the application. The AEGetTheCurrentEvent function makes it unnecessary for these calls to include the current Apple event as a parameter; the routines can simply call AEGetTheCurrentEvent to get the current Apple event when it is needed.
You can also use the AEGetTheCurrentEvent function to make sure that no Apple event is currently being handled. For example, if your application always uses an application-defined routine to delete a file, that routine can determine whether any Apple event is currently being handled by calling AEGetTheCurrentEvent, and delete the file only if AEGetTheCurrentEvent returns a null descriptor record, indicating that no Apple event is currently being handled.
RESULT CODE
noErr 0 No error
Creating Apple Events
The AECreateAppleEvent function allows you to create an Apple event.
2AECreateAppleEvent
You can use the AECreateAppleEvent function to create an Apple event with several important attributes but no parameters. You add parameters to the Apple event after you createit
FUNCTION AECreateAppleEvent (theAEEventClass: AEEventClass;
theAEEventID: AEEventID; target:
AEAddressDesc; returnID: Integer;
transactionID: LongInt;
VAR result: AppleEvent): OSErr;
theAEEventClass
The event class of the Apple event to be created.
theAEEventID
The event ID of the Apple event to be created.
target The address of the server application.
returnID The return ID assigned to this Apple event; if the kAutoGenerateReturnID constant is used as the value, the Apple Event Manager assigns a return ID that is unique to the current session.
transactionID
The transaction ID for this Apple event. A transaction is a sequence of Apple events that are sent back and forth between the client and server applications, beginning with the client’s initial request for a service. All Apple events that are part of a transaction must have the same transaction ID.
result The Apple event that the AECreateAppleEvent function creates.
DESCRIPTION
The AECreateAppleEvent function creates an Apple event.Your application is responsible for using the AEDisposeDesc function to dispose of the Apple event once you are finished with it.
If AECreateAppleEvent returns a nonzero result code, it returns a null descriptor record (a descriptor record of type typeNull, which does not contain any data) unless the Apple Event Manager is not available due to limited memory.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
SEE ALSO
See “Creating an Apple Event,” which begins on page 2-110, for more information on how to create an Apple event.
See “Specifying a Target Address” on page 2-116 for information on how to address an Apple event.
Creating and Duplicating Descriptor Records
The AECreateDesc function takes data and converts it into a descriptor record, and the AEDuplicateDesc function makes a copy of a descriptor record.
2AECreateDesc
You can use the AECreateDesc function to convert data into a descriptor record.
FUNCTION AECreateDesc (typeCode: DescType; dataPtr: Ptr;
dataSize: Size; VAR result: AEDesc): OSErr;
typeCode The descriptor type for the descriptor record.
dataPtr A pointer to the data for the descriptor record.
dataSize The length, in bytes, of the data for the descriptor record.
result The descriptor record that the AECreateDesc function creates.
DESCRIPTION
The AECreateDesc function creates a new descriptor record from the specified data. Your application is responsible for using the AEDisposeDesc function to dispose of the resulting descriptor record once you are finished with it. You normally do this after receiving a result code from the AESend function.
If AECreateDesc returns a nonzero result code, it returns a null descriptor record (a descriptor record of type typeNull, which does not contain any data) unless the Apple Event Manager is not available due to limited memory.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
2AEDuplicateDesc
You can use the AEDuplicateDesc function to make a copy of a descriptor record.
FUNCTION AEDuplicateDesc (theAEDesc: AEDesc;
VAR result: AEDesc): OSErr;
theAEDesc The descriptor record to be copied.
result The duplicate descriptor record.
DESCRIPTION
The AEDuplicateDesc function creates a new descriptor record by copying the descriptor record from the parameter theAEDesc. Your application is responsible for using the AEDisposeDesc function to dispose of the resulting descriptor record once you are finished with it. You normally do this after receiving a result code from the AESend function.
If AEDuplicateDesc returns a nonzero result code, it returns a null descriptor record (a descriptor record of type typeNull, which does not contain any data) unless the Apple Event Manager is not available due to limited memory.
It is common for applications to send Apple events that have one or more attributes or parameters in common. For example, if you send a series of Apple events to the same application, the address attribute is the same. In these cases, the most efficient way to create the necessary Apple events is to make a template Apple event that you can then copy—by calling the AEDuplicateDesc function—as needed. You then fill in or change the remaining parameters and attributes of the copy, send the copy by calling AESend, and dispose of the copy—by calling AEDisposeDesc—after AESend returns a result code.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
Creating Descriptor Lists and AE Records
The AECreateList function allows you to create an empty descriptor list or AE record.
2AECreateList
You can use the AECreateList function to create an empty descriptor list or AE record.
FUNCTION AECreateList (factoringPtr: Ptr; factoredSize: Size;
isRecord: Boolean;
VAR resultList: AEDescList): OSErr;
factoringPtr
A pointer to the data at the beginning of each descriptor that is the same for all descriptor records in the list. If there is no common data, or if you decide not to isolate the common data, provide NIL as the value of this parameter.
factoredSize
The size of the common data. If there is no common data, or if you decide not to isolate the common data, the value of factoredSize must be 0.
isRecord A Boolean value that specifies the kind of list to create. If you set it to TRUE, the Apple Event Manager creates an AE record. If you set it to FALSE, the Apple Event Manager creates a descriptor list.
resultList The descriptor list or AE record that the AECreateList function creates.
DESCRIPTION
The AECreateList function creates an empty descriptor list or AE record. Your application is responsible for using the AEDisposeDesc function to dispose of the resulting descriptor record once you are finished with it. You normally do this after receiving a result code from the AESend function.
If AECreateList returns a nonzero result code, it returns a null descriptor record (a descriptor record of type typeNull, which does not contain any data) unless the Apple Event Manager is not available due to limited memory.
RESULT CODES
noErr 0 No error
paramErr –50 Parameter error (handler pointer is NIL or odd)
memFullErr –108 Not enough room in heap zone
Creating Object Specifier Records
The Apple Event Manager provides five functions that you can use to create some of the components of an object specifier record or to assemble an object specifier record:
n The CreateOffsetDescriptor function creates an offset descriptor record, which specifies the position of an element in relation to the beginning or end of its container.
n The CreateCompDescriptor function creates a comparison descriptor record, which specifies how to compare one or more Apple event objects with either another Apple event object or a descriptor record.
n The CreateLogicalDescriptor function creates a logical descriptor record, which specifies a logical operator and one or more logical terms for the Apple Event Manager to evaluate.
n The CreateRangeDescriptor function creates a range descriptor record, which specifies a series of consecutive elements in the same container.
n The CreateObjSpecifier function assembles an object specifier record, which identifies one or more Apple event objects, from other descriptor records.
Instead of using these functions, you can create the corresponding descriptor records yourself using the AECreateDesc function, add them to an AE record using other Apple Event Manager routines, and coerce the AE record to a descriptor record of type typeObjectSpecifier. However, in most cases it is easier to use the functions listed in this section.
All of these functions except for CreateOffsetDescriptor include a disposeInputs parameter. If this parameter is TRUE, the function automatically disposes of any descriptor records you have provided as parameters to the function. If this parameter is FALSE, ther application must dispose of the records itself. This may be more efficient for some applications because it allows allows them to keep descriptor records they can reuse.
For more information about these functions and examples of their use, see “Creating an Object Specifier Record,” which begins on page 2-118.
2CreateOffsetDescriptor
You can use the CreateOffsetDescriptor function to create an offset descriptor record.
FUNCTION CreateOffsetDescriptor (theOffset: LongInt;
VAR theDescriptor: AEDesc):
OSErr;
theOffset A positive integer that specifies the offset from the beginning of the container (the first element has an offset of 1), or a negative integer that specifies the offset from the end (the last element has an offset of –1).
theDescriptor
The offset descriptor record created by CreateOffsetDescriptor.
DESCRIPTION
The CreateOffsetDescriptor function creates an offset descriptor record, which specifies the position of an element in relation to the beginning or end of its container.
RESULT CODES
noErr 0 No error occurred.
memFullErr –108 Not enough room in heap zone
2CreateCompDescriptor
You can use the CreateCompDescriptor function to create a comparison descriptor record.
FUNCTION CreateCompDescriptor (comparisonOperator: DescType;
VAR operand1: AEDesc;
VAR operand2: AEDesc;
disposeInputs: Boolean;
VAR theDescriptor: AEDesc):
OSErr;
comparisonOperator
The comparison operator for comparing the descriptor records in the operand1 and operand2 parameters. The operator is specified by the constants listed in the description that follows.
operand1 An object specifier record.
operand2 A descriptor record (which can be an object specifier record or any other descriptor record ) whose value is to be compared to the value of operand1.
disposeInputs
If TRUE, indicates that the function is to dispose of the descriptors for the two operands.
theDescriptor
The comparison descriptor record created by CreateCompDescriptor..
DESCRIPTION
The CreateCompDescriptor function creates a comparison descriptor record, which specifies how to compare one or more Apple event objects with either another Apple event object or a descriptor record.
The actual comparison of the two operands is performed by the object comparison function provided by the client application. The way a comparison operator is interpreted is up to each application.
These are the currently defined standard comparison operators:
Constant Meaning
kAEGreaterThan The value of operand1 is greater than the value of
operand2.
kAEGreaterThanEquals The value of operand1 is greater than or equal to
the value of operand2.
kAEEquals The value of operand1 is equal to the value of
operand2.
kAELessThan The value of operand1 is less than than the value of
operand2.
kAELessThanEquals The value of operand1 is less than or equal to the
value of operand2.
kAEBeginsWith The value of operand1 begins with the value of
operand2 (for example, the string "operand" begins
with the string "opera").
kAEEndsWith The value of operand1 ends with the value of
operand2 (for example, the string "operand" ends
with the string "and").
kAEContains The value of operand1 contains the value of
operand2 (for example, the string "operand"
contains the string "era").
RESULT CODES
noErr 0 No error occurred
paramErr –50 Error in parameter list
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested
Apple event data type
errAEWrongDataType –1703 Wrong Apple event data type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
SEE ALSO
For an example of how to use the CreateCompDescriptor function to create a comparison descriptor record, see “Specifying a Test,” which begins on page 2-131.
2CreateLogicalDescriptor
You can use the CreateLogicalDescriptor function to create a logical descriptor record.
FUNCTION CreateLogicalDescriptor (VAR logicalTerms: AEDescList;
logicalOperator: DescType;
disposeInputs: Boolean;
VAR theDescriptor: AEDesc):
OSErr;
logicalTerms
A list containing comparison descriptor records, logical descriptor records, or both. If the value of the parameter theLogicalOperator is kAEAnd or kAEOr, the list can contain any number of descriptors. If the value of the parameter theLogicalOperator is kAENot, this list must contain a single descriptor record.
logicalOperator
A logical operator represented by one of the following constants:
CONST kAEAND = 'AND ';
kAEOR = 'OR ';
kAENOT = 'NOT ';
disposeInputs
If TRUE, indicates that the descriptors for the other input parameters are to be disposed of by the function.
theDescriptor
The logical descriptor record created by CreateLogicalDescriptor.
DESCRIPTION
The CreateLogicalDescriptor function creates a logical descriptor record, which specifies a logical operator and one or more logical terms for the Apple event Manager to evaluate.
RESULT CODES
noErr 0 No error occurred
paramErr –50 Error in parameter list
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested
Apple event data type
errAEWrongDataType –1703 Wrong Apple event data type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
SEE ALSO
For an example of how to use the CreateLogicalDescriptor function to create a logical descriptor record, see “Specifying a Test,” which begins on page 2-131.
2CreateRangeDescriptor
You can use the CreateRangeDescriptor function to create a range descriptor record.
FUNCTION CreateRangeDescriptor (VAR rangeStart: AEDesc;
VAR rangeStop: AEDesc;
disposeInputs: Boolean;
VAR theDescriptor: AEDesc):
OSErr;
rangeStart An object specifier record that identifies the first Apple event object in the range.
rangeStop An object specifier record that identifies the last Apple event object in the range.
disposeInputs
If TRUE, indicates that the function will dispose of the descriptor records for the therangeStart and rangeStop parameters. If FALSE, indicates that your application must dispose of these descriptor records itself.
theDescriptor
The range descriptor record created by CreateRangeDescriptor.
DESCRIPTION
The CreateRangeDescriptor function creates a range descriptor record, which specifies a series of consecutive elements in the same container. Although the rangeStart and rangeStop parameters can be any object specifier records—including object specifier records that specify more than one Apple event object—most applications expect these parameters to specify single Apple event objects.
RESULT CODES
noErr 0 No error occurred
paramErr –50 Error in parameter list
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested
Apple event data type
errAEWrongDataType –1703 Wrong Apple event data type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
SEE ALSO
For an example of how to use the CreateRangeDescriptor function to create a range descriptor record, see “Specifying a Range” on page 2-141.
2CreateObjSpecifier
You can use the CreateObjSpecifier function to create an object specifier record.
FUNCTION CreateObjSpecifier (desiredClass: DescType;
VAR theContainer: AEDesc;
keyForm: DescType;
VAR keyData: AEDesc;
disposeInputs: Boolean;
VAR objSpecifier: AEDesc): OSErr;
desiredClass
The object class of the desired Apple event objects.
theContainer
The container from which to get the desired Apple event objects.
keyForm The key form for the object specifier record.
keyData The key data for the object specifier record.
disposeInputs
If TRUE, the descriptors for the other parameters are to be disposed of by the function.
objSpecifier
The object specifier record created by theCreateObjSpecifier function.
DESCRIPTION
The CreateObjSpecifier function assembles an object specifier record, which identifies one or more Apple event objects, from other descriptor records.
RESULT CODES
noErr 0 No error occurred
paramErr –50 Error in parameter list
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested
Apple event data type
errAEWrongDataType –1703 Wrong Apple event data type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
SEE ALSO
For information about the components of an object specifier record and how to assemble them with the CreateObjSpecifier function, see “Creating an Object Specifier Record,” which begins on page 2-118.
Adding Items to Descriptor Lists
The Apple Event Manager provides three routines that allow you to add descriptor records to any descriptor list, including an Apple event record. The AEPutPtr function takes data specified in a buffer, converts it to a descriptor record, and adds the descriptor record to a descriptor list. The AEPutDesc function adds a descriptor record to a descriptor list. The AEPutArray function puts the data for an Apple event array into a descriptor list.
2AEPutPtr
You can use the AEPutPtr routine to add data specified in a buffer to any descriptor list as a descriptor record.
FUNCTION AEPutPtr (theAEDescList: AEDescList; index: LongInt;
typeCode: DescType; dataPtr: Ptr;
dataSize: Size): OSErr;
theAEDescList
The descriptor list to which to add a descriptor record.
index The position in the descriptor list for the descriptor record. (For example, the value 2 specifies the second descriptor record in the list.) If there was already a descriptor record in the specified position, it is replaced. If the value of index is 0, the descriptor record is added to the end of the list.
typeCode The descriptor type for the resulting descriptor record.
dataPtr A pointer to the data for the descriptor record.
dataSize The length, in bytes, of the data for the descriptor record.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
errAEIllegalIndex –1719 Not a valid list index
2AEPutDesc
You can use the AEPutDesc function to add a descriptor record to any descriptor list.
FUNCTION AEPutDesc (theAEDescList: AEDescList; index: LongInt;
theAEDesc: AEDesc): OSErr;
theAEDescList
The descriptor list to which to add a descriptor record.
index The position in the list for the descriptor record. (For example, the value 2 specifies the second descriptor record in the list.) If there was already a descriptor record in the specified position, it is replaced. If the value of index is 0, the descriptor record is added to the end of the list.
theAEDesc The descriptor record to be added to the list.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
errAEIllegalIndex –1719 Not a valid list index
2AEPutArray
You can use the AEPutArray function to put the data for an Apple event array into any descriptor list.
FUNCTION AEPutArray (theAEDescList: AEDescList;
arrayType: AEArrayType;
arrayPtr: AEArrayDataPointer;
itemType: DescType;
itemSize: Size; itemCount: LongInt): OSErr;
theAEDescList
The descriptor list into which to put the Apple event array. If there are any items already in the descriptor list, they are replaced.
arrayType The Apple event array type to be created. This is specified by one of the following constants: kAEDataArray, kAEPackedArray, kAEHandleArray, kAEDescArray, or kAEKeyDescArray. The kAEDataArray constant refers to an array of integers; kAEPackedArray refers to an array of characters; kAEHandleArray refers to an array of handles; kAEDescArray refers to an array of descriptor records; and kAEKeyDescArray refers to an array of keyword-specified descriptor records.
arrayPtr A pointer to the buffer containing the array.
itemType For packed, data, and handle arrays, the descriptor type of array items to be created.
itemSize For packed and data arrays, the size (in bytes) of the array items to be created.
itemCount The number of elements in the array.
DESCRIPTION
If you are putting an array into a factored descriptor list, the data for each array element must include the data that is common to all the descriptor records in the list. The Apple Event Manager automatically isolates the data you specified in the call to AECreateList that is common to all the elements of the array.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
Adding Data and Descriptor Records to AE Records
The Apple Event Manager provides two routines that allow you to add data and keyword-specified descriptor records to AE records. The AEPutKeyPtr function takes a pointer to data, a descriptor type, and a keyword and converts them into a keyword-specified descriptor record that it adds to an AE record. The AEPutKeyDesc function takes a descriptor record and a keyword and converts them into a keyword-specified descriptor record that it adds to an AE record.
2AEPutKeyPtr
You can use the AEPutKeyPtr function to add a pointer to data, a descriptor type, and a keyword to an AE record as a keyword-specified descriptor record.
FUNCTION AEPutKeyPtr (theAERecord: AERecord;
theAEKeyword: AEKeyword;
typeCode: DescType; dataPtr: Ptr;
dataSize: Size): OSErr;
theAERecord
The AE record to which to add a keyword-specified
descriptor record.
theAEKeyword
The keyword that identifies the descriptor record. If the AE record already includes a descriptor record with this keyword, it is replaced.
typeCode The descriptor type for the keyword-specified descriptor record.
dataPtr A pointer to the data for the keyword-specified descriptor record.
dataSize The length, in bytes, of the data for the keyword-specified descriptor record.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
2AEPutKeyDesc
You can use the AEPutKeyDesc function to add a descriptor record and a keyword to an AE record as a keyword-specified descriptor record.
FUNCTION AEPutKeyDesc (theAERecord: AERecord;
theAEKeyword: AEKeyword;
theAEDesc: AEDesc): OSErr;
theAERecord
The AE record to which to add the keyword-specified descriptor record.
theAEKeyword
The keyword specifying the descriptor record. If there was already a keyword-specified descriptor record with this keyword, it is replaced.
theAEDesc The descriptor record for the keyword-specified descriptor record.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
Adding Parameters and Attributes to Apple Events
The Apple Event Manager provides four functions that allow you to add Apple event parameters and attributes to an Apple event. The AEPutParamPtr and AEPutParamDesc functions add parameters to a specified Apple event. The AEPutAttributePtr and AEPutAttributeDesc functions add attributes to a specified Apple event.
2AEPutParamPtr
You can use the AEPutParamPtr function to add a pointer to data, a descriptor type, and a keyword to an Apple event as an Apple event parameter.
FUNCTION AEPutParamPtr (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword;
typeCode: DescType; dataPtr: Ptr;
dataSize: Size): OSErr;
theAppleEvent
The Apple event to which to add a parameter.
theAEKeyword
The keyword for the parameter to be added. If the Apple event already included a parameter with this keyword, the parameter is replaced.
typeCode The descriptor type for the parameter.
dataPtr A pointer to the data for the parameter.
dataSize The length, in bytes, of the data for the parameter.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
2AEPutParamDesc
You can use the AEPutParamDesc function to add a descriptor record and a keyword to an Apple event as an Apple event parameter.
FUNCTION AEPutParamDesc (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword;
theAEDesc: AEDesc): OSErr;
theAppleEvent
The Apple event to which to add a parameter.
theAEKeyword
The keyword for the parameter to be added. If the Apple event already included a parameter with this keyword, the parameter is replaced.
theAEDesc The descriptor record for the parameter.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEWrongDataType –1703 Wrong descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
2AEPutAttributePtr
You can use the AEPutAttributePtr function to add a pointer to data, a descriptor type, and a keyword to an Apple event as an attribute.
FUNCTION AEPutAttributePtr (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword;
typeCode: DescType;
dataPtr: Ptr; dataSize: Size): OSErr;
theAppleEvent
The Apple event to which to add an attribute.
theAEKeyword
The keyword for the attribute to be added. If th Apple event already included an attribute with this keyword, the attribute is replaced. The keyword can be any of the keywords listed in the description that follows.
typeCode The descriptor type for the attribute.
dataPtr A pointer to the buffer containing the data to be assigned to the attribute.
dataSize The length, in bytes, of the data to be assigned to the attribute.
DESCRIPTION
The AEPutAttributePtr function adds the specified pointer to data, descriptor type, and keyword to the specified Apple event as an attribute. The keyword can be one of the following:
Attribute keyword Value Description
keyAddressAttr 'addr' Address of target application
keyEventClassAttr 'evcl' Event class of Apple event
keyEventIDAttr 'evid' Event ID of Apple event
keyEventSourceAttr 'esrc' Source of the Apple event
keyInteractLevelAttr 'inte' Settings for allowing the Apple Event
Manager to bring a server application
to the foreground
keyMissedKeywordAttr 'miss' First required parameter remaining in
an Apple event
keyOptionalKeywordAttr 'optk' List of optional parameters
for the Apple event
keyReturnIDAttr 'rtid' Return ID for reply Apple event
keyTimeoutAttr 'timo' Length of time in ticks that the client
will wait for a reply or a result from
the server
keyTransactionIDAttr 'tran' Transaction ID identifying a series of
Apple events
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested
descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
2AEPutAttributeDesc
You can use the AEPutAttributeDesc function to add a descriptor record and a keyword to an Apple event as an attribute.
FUNCTION AEPutAttributeDesc (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword;
theAEDesc: AEDesc): OSErr;
theAppleEvent
The Apple event to which you are adding an attribute.
theAEKeyword
The keyword of the attribute. If the Apple event already included an attribute with this keyword, the attribute is replaced.
theAEDesc The descriptor record to be assigned to the attribute. The descriptor type of the specified descriptor record should match the defined descriptor type for that attribute. For example, the keyEventSourceAttr attribute has the typeShortInteger descriptor type.
DESCRIPTION
The AEPutAttributeDesc function takes a descriptor record and a keyword and adds them to an Apple event as an attribute. If the descriptor type required for the attribute is different from the descriptor type of the descriptor record, the Apple Event Manager attempts to coerce the descriptor record into the required type, with one exception: the Apple Event Manager does not attempt to coerce the data for an address attribute, thereby allowing applications to use their own address types.
The keyword can be one of the following:
Attribute keyword Value Description
keyAddressAttr 'addr' Address of target application
keyEventClassAttr 'evcl' Event class of Apple event
keyEventIDAttr 'evid' Event ID of Apple event
keyEventSourceAttr 'esrc' Source of the Apple event
keyInteractLevelAttr 'inte' Settings for allowing the Apple Event
Manager to bring a server application
to the foreground
keyMissedKeywordAttr 'miss' First required parameter remaining in
an Apple event
keyOptionalKeywordAttr 'optk' List of optional parameters
for the Apple event
keyReturnIDAttr 'rtid' Return ID for reply Apple event
keyTimeoutAttr 'timo' Length of time in ticks that the client
will wait for a reply or a result from
the server
keyTransactionIDAttr 'tran' Transaction ID identifying a series of
Apple events
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested
descriptor type
errAENotAEDesc –1704 Not a valid descriptor record
Sending Apple Events
The AESend function allows you to send an Apple event that you have previously created with the AECreateAppleEvent function.
2AESend
You can use the AESend function to send an Apple event.
FUNCTION AESend (theAppleEvent: AppleEvent;
VAR reply: AppleEvent; sendMode: AESendMode;
sendPriority: AESendPriority;
timeOutInTicks: LongInt; idleProc: IdleProcPtr;
filterProc: EventFilterProcPtr): OSErr;
theAppleEvent
The Apple event to be sent.
reply The reply Apple event returned by the AESend function if you specify the kAEWaitReply flag in the sendMode parameter. (If you specify the kAEQueueReply flag in the sendMode parameter, you receive the reply Apple event in your event queue.) If you specify kAENoReply flag, the reply Apple event returned by this function is a null descriptor record—that is, a descriptor record of descriptor type typeNull, which does not contain data. If you specify kAEWaitReply in the sendMode parameter, your application is responsible for using the AEDisposeDesc function to dispose of the descriptor record returned in the reply parameter.
sendMode Specifies the following: the reply mode for the Apple event (set with one of the constants kAENoReply, kAEQueueReply, or kAEWaitReply); the interaction level (set with one of the constants kAENeverInteract, kAECanInteract, or kAEAlwaysInteract, which represent flags in the keyInteractLevelAttr attribute); the application switch mode (set with the kAECanSwitchLayer constant); the reconnection mode (set with the kAEDontReconnect constant); and the return receipt mode (set with the kAEWantReceipt constant). You obtain the value for this parameter by adding the appropriate constants. (The description that follows provides more details about the sendMode flags.)
sendPriority
Specifies whether the Apple event is put at the back of the event queue (indicated by the kAENormalPriority flag) or at the front of the queue (indicated by the kAEHighPriority flag).
timeOutInTicks
If the reply mode specified in the sendMode parameter is kAEWaitReply, or if a return receipt is requested, this parameter specifies the length of time (in ticks) that the client application is willing to wait for the reply or return receipt from the server application before timing out. Most applications should use the kAEDefaultTimeout constant, which tells the Apple Event Manager to provide an appropriate timeout duration. If the value of this parameter is kNoTimeOut, the Apple event never times out.
idleProc A pointer to a function for any tasks (such as displaying a wristwatch or spinning beachball cursor) that the application performs while waiting for a reply or a return receipt.
filterProc A pointer to a routine that accepts certain incoming Apple events that are received while the handler waits for a reply or a return receipt and filters out the rest.
DESCRIPTION
You can use one of the following flags in the sendMode parameter to specify the reply mode for an Apple event. Only one of these flags may be set.
Flag Description
kAENoReply Your application does not want a reply Apple event;
the server processes your Apple event as soon as it
has the opportunity.
kAEQueueReply Your application wants a reply Apple event; the reply
appears in your event queue as soon as the server has
the opportunity to process and respond to your Apple
event.
kAEWaitReply Your application wants a reply Apple event and is
willing to give up the processor while waiting for the
reply; for example, if the server application is on the
same computer as your application, your application
yields the processor to allow the server to respond to
your Apple event.
You can communicate your user-interaction preferences to the server application by specifying one of these flags in the sendMode parameter of the AESend function. Only one of these flags may be set.
Flag Description
kAENeverInteract The server application should never interact with the
user in response to this Apple event. If this flag is set,
AEInteractWithUser returns the
errAENoUserInteraction result code. This flag is
the default when an Apple event is sent to a remote
application.
kAECanInteract The server application can interact with the user in
response to this Apple event—by convention, if the
user needs to supply information to the server. If this
flag is set and the server allows interaction,
AEInteractWithUser either brings the server
application to the foreground or posts a notification
request. This flag is the default when an Apple event is
sent to a local application.
kAEAlwaysInteract The server application can interact with the user in
response to this Apple event—by convention,
whenever the server application normally asks a user
to confirm a decision or interact in any other way,
even if no additional information is needed from
the user. If this flag is set and the server allows
interaction, AEInteractWithUser either brings the
server application to the foreground or posts a
notification request.
The flags in the following list specify the application switch mode, the reconnection mode, and the return receipt mode. Any of these flags may be set.
Flag Description
kAECanSwitchLayer If both the client and server allow interaction, and if
the client application is the active application on the local machine and is waiting for a reply (that is, it has set the kAEWaitReply flag), AEInteractWithUser brings the server directly to the foreground. Otherwise, AEInteractWithUser uses the Notification Manager to request that the user bring the server application to the foreground.
kAEDontReconnect The Apple Event Manager must not
automatically try to reconnect if it receives a
sessClosedErr result code from the PPC Toolbox.
kAEWantReceipt The sender wants to receive a return receipt for this
Apple event from the Event Manager. (Getting a
return receipt means only that the receiving
application accepted the Apple event; the Apple event
may or may not be handled successfully after it is
accepted.) If the receiving application does not send a
return receipt before the request times out, AESend
returns errAETimeout as its function result.
If the Apple Event Manager cannot find a handler for an Apple event in either the application or system Apple event dispatch table, it returns the result code errAEEventNotHandled to the server application (as the result of the AEProcessAppleEvent function). If the client application is waiting for a reply, the Apple Event Manager also returns this result code to the client.
AESend returns noErr as the function result if the Apple event was successfully sent by the Event Manager. A noErr result from AESend does not indicate that the Apple event was handled successfully; it only indicates that the Apple event was successfully sent by the Event Manager. If a result code other than noErr is returned by the handler, and if the client is waiting for a reply, it is returned in the keyErrorNumber parameter of the reply Apple event.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
connectionInvalid –609 Connection is invalid
errAEEventNotHandled –1708 Event wasn’t handled by an Apple event
handler
errAEUnknownSendMode –1710 Invalid sending mode was passed
errAEWaitCanceled –1711 User canceled out of wait loop for reply
or receipt
errAETimeout –1712 Apple event timed out
errAEUnknownAddressType –1716 Unknown Apple event address type
SEE ALSO
For more information on sending Apple events, see “Sending an Apple Event,” which begins on page 2-143.
For information on writing an idle function, see “Writing an Idle Function” on page 2-150.
For information on writing a reply filter function, see “Writing a Reply Filter Function” on page 2-152.
Getting the Sizes and Descriptor Types of Descriptor Records
The Apple Event Manager provides four routines that allow you to get the sizes and descriptor types of descriptor records that are not part of an Apple event record. The AESizeOfNthItem function returns the size and descriptor type of a descriptor record in a descriptor list. The AESizeOfKeyDesc function returns the size and descriptor type of a keyword-specified descriptor record in an AE record. The AESizeOfAttribute function returns the size and descriptor type of an Apple event attribute. The AESizeOfParam function returns the size and descriptor type of an Apple event parameter.
2AESizeOfNthItem
You can use the AESizeOfNthItem function to get the size and descriptor type of a descriptor record in a descriptor list.
FUNCTION AESizeOfNthItem (theAEDescList: AEDescList;
index: LongInt; VAR typeCode: DescType;
VAR dataSize: Size): OSErr;
theAEDescList
The descriptor list containing the descriptor record.
index The position of the descriptor record in the list (for example, 2 specifies the second descriptor record).
typeCode The descriptor type of the descriptor record.
dataSize Tthe length (in bytes) of the data in the descriptor record.
RESULT CODES
noErr 0 No error
errAEDescNotFound –1701 Descriptor record was not found
errAEReplyNotArrived –1718 Reply has not yet arrived
2AESizeOfKeyDesc
You can use the AESizeOfKeyDesc function to get the size and descriptor type of a keyword-specified descriptor record in an AE record.
FUNCTION AESizeOfKeyDesc (theAERecord: AERecord;
theAEKeyword: AEKeyword;
VAR typeCode: DescType;
VAR dataSize: Size): OSErr;
theAERecord
The AE record containing the desired keyword-specified descriptor record.
theAEKeyword
The keyword that specifies the desired descriptor record.
typeCode The descriptor type of the keyword-specified descriptor record.
dataSize The length (in bytes) of the data in the keyword-specified descriptor record.
RESULT CODES
noErr 0 No error
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
2AESizeOfParam
You can use the AESizeOfParam function to get the size and descriptor type of an Apple event parameter.
FUNCTION AESizeOfParam (theAppleEvent: AppleEvent; theAEKeyword:
AEKeyword; VAR typeCode: DescType;
VAR dataSize: Size): OSErr;
theAppleEvent
The Apple event containing the parameter.
theAEKeyword
The keyword that specifies the desired parameter.
typeCode The descriptor type of the Apple event parameter.
dataSize The length, in bytes, of the data in the Apple event parameter.
RESULT CODES
noErr 0 No error
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
2AESizeOfAttribute
You can use the AESizeOfAttribute function to get the size and descriptor type of an Apple event attribute.
FUNCTION AESizeOfAttribute (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword;
VAR typeCode: DescType;
VAR dataSize: Size): OSErr;
theAppleEvent
The Apple event containing the desired attribute.
theAEKeyword
The keyword that specifies the attribute.
typeCode The descriptor type of the attribute.
dataSize The length, in bytes, of the data in the attribute.
RESULT CODES
noErr 0 No error
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEReplyNotArrived –1718 Reply has not yet arrived
Deleting Descriptor Records
The Apple Event Manager provides three functions that allow you to delete descriptor records from a descriptor list, an AE record, or an Apple event parameter. The AEDeleteItem function deletes a descriptor record from a descriptor list. The AEDeleteKeyDesc function deletes a keyword-specified descriptor record from an AE record. The AEDeleteParam function deletes an Apple event parameter.
2AEDeleteItem
You can use the AEDeleteItem function to delete a descriptor record from a descriptor list.
FUNCTION AEDeleteItem (theAEDescList: AEDescList;
index: LongInt): OSErr;
theAEDescList
The descriptor list containing the descriptor record to be deleted.
index The position of the descriptor record to delete (for example, 2 specifies the second item).
RESULT CODES
noErr 0 No error
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item failed
2AEDeleteKeyDesc
You can use the AEDeleteKeyDesc function to delete a keyword-specified descriptor record from an AE record.
FUNCTION AEDeleteKeyDesc (theAERecord: AERecord;
theAEKeyword: AEKeyword): OSErr;
theAERecord
The AE record containing the keyword-specified descriptor record to be deleted.
theAEKeyword
The keyword that specifies the descriptor record to be deleted.
RESULT CODES
noErr 0 No error
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
badListItem –1705 Operation involving a list item failed
2AEDeleteParam
You can use the AEDeleteParam function to delete an Apple event parameter.
FUNCTION AEDeleteParam (theAppleEvent: AppleEvent;
theAEKeyword: AEKeyword): OSErr;
theAppleEvent
The Apple event containing the parameter to be deleted.
theAEKeyword
The keyword that specifies the parameter to be deleted.
RESULT CODES
noErr 0 No error
errAEDescNotFound –1701 Descriptor record was not found
errAENotAEDesc –1704 Not a valid descriptor record
errAEBadListItem –1705 Operation involving a list item
failed
Deallocating Memory for Descriptor Records
The AEDisposeDesc function deallocates the memory used by a descriptor record. Because all Apple event structures (except for keyword-specified descriptor records) are descriptor records, you can use AEDisposeDesc for any of them.
2AEDisposeDesc
You can use the AEDisposeDesc function to deallocate the memory used by a descriptor record.
FUNCTION AEDisposeDesc (VAR theAEDesc: AEDesc): OSErr;
theAEDesc The descriptor record to deallocate.
RESULT CODE
noErr 0 No error
Deallocating Memory for Tokens
Whenever the AEResolve function returns a token to your event handler as the final result of the resolution of an object specifier record passed to AEResolve, your application should call the AEDisposeToken function to deallocate the memory used by the token.
2AEDisposeToken
You can use the AEDisposeToken function to deallocate the memory used by a token.
FUNCTION AEDisposeToken (VAR theToken: AEDesc): OSErr;
theToken The token to be disposed of.
DESCRIPTION
When your application calls the AEDisposeToken function, the Apple Event Manager first calls your application’s token disposal function (the MyDisposeToken function described on page 2-260) if you haveprovided one. If you haven’t provided a token disposal function, or if your application’s token disposal function returns errAEEventNotHandled as the function result, the Apple Event Manager calls the system token disposal function if one is available. If there is no system token disposal function or the function returns errAEEventNotHandled as the function result, the Apple Event Manager calls the AEDisposeDesc function to dispose of the token.
RESULT CODES
noErr 0 No error occurred
paramErr –50 AEObjectInit was not called before this
function was called
notASpecialFunction –1714 Wrong keyword for a special function
In addition to these result codes, AEDisposeToken also returns result codes returned by the token disposal function that disposed of the token.
Coercing Descriptor Types
The Apple Event Manager provides two functions that allow you to coerce descriptor types. The AECoercePtr function takes a pointer to data and a desired descriptor type and attempts to coerce the data into the desired descriptor type. The AECoerceDesc function attempts to coerce the data in a descriptor record to another descriptor type.
2AECoercePtr
You can use the AECoercePtr function to coerce data into a desired descriptor type. If successful, it creates a descriptor record containing the newly coerced data.
FUNCTION AECoercePtr (typeCode: DescType; dataPtr: Ptr;
dataSize: Size; toType: DescType;
VAR result: AEDesc): OSErr;
typeCode The descriptor type of the source data.
dataPtr A pointer to the data to be coerced.
dataSize The length, in bytes, of the data to be coerced.
toType The desired descriptor type of the resulting descriptor record.
result The resulting descriptor record.
DESCRIPTION
This function creates a new descriptor record by coercing the specified data. Your application is responsible for using the AEDisposeDesc function to dispose of the resulting descriptor record once you are finished using it.
If AECoercePtr returns a nonzero result code, it returns a null descriptor record (a descriptor record of type typeNull, which does not contain any data) unless the Apple Event Manager is not available due to limited memory.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested
descriptor type
2AECoerceDesc
You can use the AECoerceDesc function to coerce the data in a descriptor record to another descriptor type.
FUNCTION AECoerceDesc (theAEDesc: AEDesc; toType: DescType;
VAR result: AEDesc): OSErr;
theAEDesc The descriptor record whose data is to be coerced.
toType The desired descriptor type of the resulting descriptor record.
result The resulting descriptor record.
DESCRIPTION
The AECoerceDesc function creates a new descriptor record by coercing the specified descriptor record. Your application is responsible for using the AEDisposeDesc function to dispose of the resulting descriptor record once you are finished using it.
If AECoerceDesc returns a nonzero result code, it returns a null descriptor record (a descriptor record of type typeNull, which does not contain any data) unless the Apple Event Manager is not available due to limited memory.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAECoercionFail –1700 Data could not be coerced to the requested
descriptor type
Creating and Managing the Coercion Handler Dispatch Tables
The Apple Event Manager provides three functions that allow you to create and manage the coercion handler dispatch tables. The AEInstallCoercionHandler function installs a coercion handler routine in either the application or system coercion dispatch table. The AEGetCoercionHandler function returns the handler for a specified descriptor type coercion. The AERemoveCoercionHandler function removes a coercion handler from either the application or system coercion table.
2AEInstallCoercionHandler
You can use the AEInstallCoercionHandler function to install a coercion handler routine in either the application or system coercion handler dispatch table.
FUNCTION AEInstallCoercionHandler (fromType: DescType;
toType: DescType;
handler: ProcPtr;
handlerRefcon: LongInt;
fromTypeIsDesc: Boolean;
isSysHandler: Boolean): OSErr;
fromType The descriptor type of the data coerced by the handler.
toType The descriptor type of the resulting data. If there was already an entry in the specified coercion handler table for the same source descriptor type and result descriptor type, it is replaced.
handler A pointer to the coercion handler. Note that a handler in the system coercion table must reside in the system heap; this means that if the value of the isSysHandler parameter is TRUE, the handler parameter should point to a location in the system heap. Otherwise, if you put your system handler code in your application heap, you must remove the handler when your application quits by using the AERemoveCoercionHandler function.
handlerRefcon
A reference constant that is passed by the Apple Event Manager to the handler each time the handler is called. If your handler doesn’t expect a reference constant, use 0 as the value of this parameter.
fromTypeIsDesc
Specifies the form of the data to be coerced. If the value of this parameter is TRUE, the coercion handler expects the data to be passed as a descriptor record. If the value is FALSE, the coercion handler expects a pointer to the data to be coerced. Because it is more efficient for the Apple Event Manager to provide a pointer to data than to a descriptor record, all coercion routines should accept a pointer to data if possible.
isSysHandler
Specifies the coercion table to which to add the handler. If the value of this parameter is TRUE, the handler is added to the system coercion table and made available to all applications. If the value is FALSE, the handler is added to the application coercion table. Note that a handler in the system coercion table must reside in the system heap; this means that if the value of the isSysHandler parameter is TRUE, the handler parameter must point to a location in the system heap.
DESCRIPTION
Before using AEInstallCoercionHandler to install a handler for a particular descriptor type into the system coercion handler dispatch table, use the AEGetCoercionHandler function to determine whether the table already contains a coercion handler for that descriptor type. If an entry exists, AEGetCoercionHandler returns a reference constant and a pointer to that handler. Chain these to your coercion handler by providing pointers to the previous handler and its reference constant in the handlerRefcon parameter of AEInstallCoercionHandler. If your coercion handler returns the error errAECoercionFail, use these pointers to call the previous handler. If you remove your system coercion handler, be sure to reinstall the chained handlers.
When an application calls a system coercion handler, the A5 register is set up for the calling application. For this reason, if you provide a system coercion handler, it should never use A5 global variables or anything that depends on a particular context; otherwise, the application that calls the system handler may crash.<36pt\>\x12 <8bat\>u
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
2AEGetCoercionHandler
You can use the AEGetCoercionHandler function to get the handler for a specified descriptor type coercion.
FUNCTION AEGetCoercionHandler (fromType: DescType;
toType: DescType;
VAR handler: ProcPtr;
VAR handlerRefcon: LongInt;
VAR fromTypeIsDesc: Boolean;
isSysHandler: Boolean): OSErr;
fromType The descriptor type of the data coerced by the handler
toType The descriptor type of the resulting data.
handler A pointer to the desired coercion handler.
handlerRefcon
The reference constant for the desired handler. The Apple Event Manager passes this reference constant to the handler each time the handler is called.
fromTypeIsDesc
If the AEGetCoercionHandler function returns TRUE in this parameter, the coercion handler expects the data to be passed as a descriptor record. If the function returns FALSE, the coercion handler expects a pointer to the data.
isSysHandler
Specifies the coercion table from which to get the handler. If the value of this parameter is TRUE, the handler is taken from the system coercion table. If the value is FALSE, the handler is taken from the application coercion table.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEHandlerNotFound –1717 No coercion handler found
2AERemoveCoercionHandler
You can use the AERemoveCoercionHandler function to remove a coercion handler from either the application or system coercion handler dispatch table.
FUNCTION AERemoveCoercionHandler (fromType: DescType;
toType: DescType;
handler: ProcPtr;
isSysHandler: Boolean): OSErr;
fromType The descriptor type of the data coerced by the handler.
toType The descriptor type of the resulting data.
handler A pointer to the coercion handler. Although the fromType and toType parameters would be sufficient to identify the handler to be removed, providing the handler parameter is a safeguard to ensure that you remove the correct handler.
isSysHandler
The coercion table from which to remove the handler. If the value of this parameter is TRUE, the handler is removed from the system coercion table. If the value is FALSE, the handler is removed from the application coercion dispatch table.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAEHandlerNotFound –1717 No coercion handler found
Creating and Managing the Special Handler Dispatch Tables
The Apple Event Manager provides three functions that allow you to create and manage the special handler dispatch tables. The AEInstallSpecialHandler function installs an entry for a special handler in either the application or system special handler dispatch table. The AEGetSpecialHandler function returns the handler for a specified special handler. The AERemoveSpecialHandler function removes a special handler from either the application or system special handler dispatch table.
You can also use the AEInstallSpecialHandler, AEGetSpecialHandler, and AERemoveSpecialHandler functions to install, get, and remove object callback functions—including system object callback functions, which cannot be installed with the AESetObjectCallback function. When using any of these functions to install, get, or remove object callback functions, use one of the following constants as the value of the functionClass parameter to specify the object callback function:
Object callback function Constant
Object-counting function keyAECountProc
Object comparison function keyAECompareProc
Token disposal function keyDiposeTokenProc
Error callback function keyAEGetErrDescProc
Mark token function keyAEMarkTokenProc
Object-marking function keyAEMarkProc
Mark-adjusting function keyAEAdjustMarksProc
You can also use the AERemoveSpecialHandler function to disable all the Apple Event Manager routines that support Apple event objects. To do this, specify the constant keySelectProc in the functionClass parameter as described on page 2-253.
2AEInstallSpecialHandler
You can use the AEInstallSpecialHandler function to install a special handler in either the application or system special handler dispatch table.
FUNCTION AEInstallSpecialHandler (functionClass: AEKeyword;
handler: ProcPtr;
isSysHandler: Boolean): OSErr;
functionClass
The keyword for the special handler that isinstalled. There is currently only one value allowed for this parameter: the keyPreDispatch constant, which identifies a handler routine that is called immediately before the Apple Event Manager dispatches an Apple event. If there was already an entry in the specified special handler dispatch table for the same value of functionClass, it is replaced.
handler A pointer to the special handler. Note that a handler in the system special handler dispatch table must reside in the system heap; this means that if the value of the isSysHandler parameter is TRUE, the handler parameter should point to a location in the system heap. Otherwise, if you put your system handler code in your application heap, you must remove the handler when your application quits by using the AERemoveSpecialHandler function.
isSysHandler
The special handler dispatch table to which to add the handler. If the value of this parameter is TRUE, the handler is added to the system handler dispatch table and made available to all applications. If the value is FALSE, the handler is added to the application handler table.
When an application calls a system special handler, the A5 register is set up for the calling application. For this reason, if you provide a system special handler, it should never use A5 global variables or anything that depends on a particular context; otherwise, the application that calls the system handler may crash.<36pt\>\x12 <8bat\>u
RESULT CODES
noErr 0 No error
paramErr –50 Parameter error (handler pointer is NIL or
odd)
memFullErr –108 Not enough room in heap zone
errAENotASpecialFunction –1714 Wrong keyword for a special function
2AEGetSpecialHandler
You can use the AEGetSpecialHandler function to get a specified special handler.
FUNCTION AEGetSpecialHandler (functionClass: AEKeyword;
VAR handler: ProcPtr;
isSysHandler: Boolean): OSErr;
functionClass
The keyword that specifies the desired special handler. There is currently only one value allowed for this parameter: the keyPreDispatch constant, which identifies a handler routine that is called immediately before the Apple Event Manager dispatches an Apple event.
handler A pointer to the special handler.
isSysHandler
Specifies the special handler dispatch table from which to get the handler. If the value of this parameter is TRUE, the handler is taken from the system special handler dispatch table. If the value is FALSE, the handler is taken from the application special handler dispatch table.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAENotASpecialFunction –1714 Wrong keyword for a special handler
2AERemoveSpecialHandler
You can use the AERemoveSpecialHandler function to remove a handler from a special handler table.
FUNCTION AERemoveSpecialHandler (functionClass: AEKeyword;
handler: ProcPtr;
isSysHandler: Boolean): OSErr;
functionClass
The keyword for the special handler to be removed. There are currently two values allowed for the functionClass parameter: keyPreDispatch and keySelectProc. The keyPreDispatch constant identifies a handler that is called immediately before the Apple Event Manager dispatches an Apple event. The keySelectProc constant indicates that you want to disable the Object Support Library —that is, all the routines that support Apple event objects (see the description that follows for more information about how to do this)
handler A pointer to the special handler to be removed. Although the functionClass parameter would be sufficient to identify the handler to be removed, providing the handler parameter is a safeguard to ensure that you remove the correct handler.
isSysHandler
Specifies the special handler dispatch table from which to remove the handler. If the value of this parameter is TRUE, the handler is taken from the system special handler dispatch table. If the value is FALSE, the handler is removed from the application special handler dispatch table.
DESCRIPTION
In addition to using the AERemoveSpecialHandler function to remove specific special handlers, you can use the function to disable all Apple Event Manager routines that support Apple event objects—that is, all the routines available to your application as a result of linking the Object Support Library (OSL) and calling the AEObjectInit function.
An application that expects its copy of the OSL to move after it is installed—for example, an application that keeps it in a stand-alone code resource—would need to do this. When an application calls AEObjectInit to initialize the OSL, the OSL installs the addresses of its routines as extensions to the pack. If those routines move, the addresses become invalid.
In order to disable the OSL, you should pass the keyword keySelectProc in the functionClass parameter, NIL in the handler parameter, and FALSE in the isSysHandler parameter. Once you have called the AERemoveSpecialHandler function with these parameters, subsequent calls to any of the Apple Event Manager routines that support Apple event objects will return errors. To initialize the OSL after disabling it with the AERemoveSpecialHandler function, your application must call AEObjectInit again.
If you expect to initialize the Object Support library and disable it several times, you should remove your application’s object accessor functions from your application’s object accessor dispatch table using the AERemoveObjectAccessor function before you call AERemoveSpecialHandler.
RESULT CODES
noErr 0 No error
memFullErr –108 Not enough room in heap zone
errAENotASpecialFunction –1714 Wrong keyword for a special function
Application-Defined Functions
The AEResolve function performs tasks that are required to resolve any object specifier record, such as parsing its contents, keeping track of the results of tests, and handling memory management. When necessary, AEResolve calls application-defined functions to perform tasks that are unique to the application, such as locating a specific Apple event object in the application’s data structures or counting the number of Apple event objects in a container.
AEResolve can call two kinds of application-defined functions:
n Object accessor functions locate Apple event objects. Every application that supports simple object specifier records must provide one or more object accessor functions.
n Object callback functions perform other tasks that only an application can perform, such as counting, comparing, or marking Apple event objects. You can provide up to seven object callback functions, depending on the needs of your application.
This section provides model declarations for the object accessor functions and object callback functions that your application can provide.
Object Accessor Functions
You must provide one or more object accessor functions that can locate all the element classes and properties listed in the Apple Event Registry: Standard Suites for the object classes supported by your application. This section provides a declaration for the object accessor functions that your application can provide.
2MyObjectAccessor
Object accessor functions locate Apple event objects of a specified object class in a container identified by a token of a specified descriptor type.
FUNCTION MyObjectAccessor (desiredClass: DescType;
containerToken: AEDesc;
containerClass: DescType;
keyForm: DescType; keyData: AEDesc;
VAR theToken: AEDesc;
theRefcon: LongInt): OSErr;
desiredClass
The object class of the desired Apple event object or objects.
containerToken
A token that specifies the container of the desired Apple event object or objects.
containerClass
The object class of the container.
keyForm The key form specified by the object specifier record being resolved.
keyData The key data specified by the object specifier record being resolved..
theRefcon A reference constant that the Apple Event Manager passes to the object accessor function each time it is called.
theToken The token returned by the MyObjectAccessor function.
DESCRIPTION
Each object accessor function provided by your application should either find elements of a specified object class or find properties of an Apple event object. The AEResolve function uses the object class ID of the specified Apple event object and the descriptor type of the token that identifiesthe object’s container to determine which object accessor function to call. To install an object accessor function either in your application’s object accessor dispatch table or in the system object accessor dispatch table, use the AEInstallObjectAccessor function, which is described on page 2-189.
RESULT CODES
noErr 0 No error occurred.
errAEEventNotHandled –1708 The object accessor function is unable to
locate the requested Apple event object or
objects; if the Apple Event Manager receives
this result, it attempts to use other methods of
locating them, such as calling an equivalent
system object accessor function
SEE ALSO
For information about installing object accessor functions, see “Installing Entries in the Object Accessor Dispatch Tables,” which begins on page 2-66.
For information about writing object accessor functions, see “Writing Object Accessor Functions,” which begins on page 2-157.
Object Callback Functions
If an Apple event parameter consists of an object specifier record, your handler for the Apple event typically calls AEResolve to begin the process of locating the requested Apple event object or objects. AEResolve in turn calls object accessor functions and, if necessary, object callback functions provided by your application when it needs the information they can provide.
This section provides declarations for the seven object callback functions that your application can provide:
n The object-counting function (MyCountObjects) counts the number of elements of a specified class in a specified container, so that the Apple Event Manager can determine how many elements it must examine to find the element or elements that pass a test. Your application must provide one object-counting function if it supports complete object specifier records.
n The object comparison function (MyCompareObjects) compares one element to another element or to a descriptor record. Your application must provide one object compoarison function if it supports complete object specifier records.
n The token disposal function (MyDisposeToken) disposes of a token after either the Apple Event Manager or your application calls the AEDisposeToken function. If no token disposal function is available, the Apple Event Manager uses the AEDisposeDesc function instead. Your application must provide one token disposal function if it supports object marking or if disposing of some of its tokens requires more than a call to AEDisposeDesc.
n The error callback function (MyGetErrorDesc) gives the Apple Event Manager an address to which to write the descriptor record it is currently working with if an error occurs while AEResolve is attempting to resolve an object specifier record. Your application is not required to provide an error callback function.
n The mark token function (MyGetMarkToken) gets a mark token that identifies the way your application marks Apple event objects during the current session while resolving a single object specifier record that specifies a test. Your application must provide this function if it supports marking.
n The object-marking function (MyMark) marks a specified Apple event object. Your application must provide this function if it supports marking.
n The mark-adjusting function (MyAdjustMarks) adjusts the marks made with the current mark token. Your application must provide this function if it supports marking.
For information about writing and installing object callback functions, see “Writing Object Callback Functions,” which begins on page 2-173.
2 MyCountObjects
If your application supports complete object specifier records, you must provide one object-counting function. An object-counting function counts the number of Apple event objects of a specified class in a specified container.
FUNCTION MyCountObjects (desiredClass: DescType;
containerClass: DescType;
theContainer: AEDesc;
VAR result: LongInt): OSErr;
desiredClass
The object class of the Apple event objects to be counted.
containerClass
The object class of the container for the Apple event objects to be counted
containerToken
A token that identifies the container for the Apple event objects to be counted.
result The number of Apple objects of the specified class that the MyCountObjects counted in the specified container.
DESCRIPTION
The Apple Event Manager calls your object-counting function whenever it is resolving an object specifier record and, in order to perform a test, requires a count of the number of Apple event objects of a given class in a given container.
RESULT CODES
noErr 0 No error occurred.
errAEEventNotHandled –1708 The object-counting function is unable to
count the specified Apple event objects; if
the Apple Event Manager receives this result,
it attempts to use other methods of counting
the Apple event objects, such as calling an
equivalent system object-counting function
SEE ALSO
For more information, see “Writing an Object-Counting Function” on page 2-175.
2MyCompareObjects
If your application supports complete object specifier records, you must provide one object comparison function. An object comparison function compares one Apple event object to another Apple event object or to a descriptor record and returns TRUE or FALSE.
FUNCTION MyCompareObjects (comparisonOperator: DescType;
object: AEDesc;
objectOrDescToCompare: AEDesc;
VAR result: Boolean): OSErr;
comparisonOperator
The comparison operator. The current version of the Apple Event Registry: Standard Suites lists all the constants for comparison operators. Constants for standard comparison operators listed at the time of publication of this book are also summarized in the description that follows.
object An object specifier record.
objectOrDescToCompare
An object specifier record or some other descriptor record that specifies either an Apple event object or a value to compare to the Apple event object specified by the object parameter.
result If TRUE, the values of theobject and objectOrDescToCompare parameters have the relationship specified by the comparisonOperator parameter; if FALSE, they do not.
DESCRIPTION
The Apple Event Manager calls your object comparison function whenever it is resolving an object specifier record and, in order to perform a test, needs to compare an Apple event object with another Apple event object or with a value.
It is up to your application to interpret the comparison operators it receives. The meaning of comparison operators differs depending on the Apple event objects being compared, and not all comparison operators apply to all object classes.
The following are the standard comparison operators defined in the Apple Event Registry: Standard Suites at the time this book is published. Future versions of the Apple Event Registry may include additional comparison operators.
Constant Meaning
kAEGreaterThan The value of the first operand is greater than the
value of the second operand.
kAEGreaterThanEquals The value of the first operand is greater than or equal
to the value of the second operand.
kAEEquals The value of the first operand is equal to the value of
the second operand.
kAELessThan The value of the first operand is less than the
value of the second operand.
kAELessThanEquals The value of the first operand is less than or equal to
the value of the second operand.
kAEBeginsWith The value of the first operand begins with the value
of the second operand (for example, the string
"operand" begins with the string "opera").
kAEEndsWith The value of the first operand ends with the value of
the second operand (for example, the string
"operand" ends with the string "and").
kAEContains The value of the first operand contains the value of
the second operand (for example, the string
"operand" contains the string "era").
RESULT CODES
noErr 0 No error occurred
errAEEventNotHandled –1708 The object comparison function is unable
to compare the specified Apple event
objects; if the Apple Event Manager gets
this result, it attempts to use other methods
of comparison, such as calling an
equivalent system object comparison
function
SEE ALSO
For more information, see “Writing an Object Comparison Function” on page 2-177.
2MyDisposeToken
If your application requires more than a call to the AEDisposeDesc function to dispose of a token, or if it supports marking callback functions, you must provide one token disposal function. A token disposal function disposes of a specified token.
FUNCTION MyDisposeToken (VAR unneededToken: AEDesc): OSErr;
unneededToken
The token to dispose of.
DESCRIPTION
The Apple Event Manager calls your token disposal function whenever it needs to dispose of a token. It also calls your disposal function when your application calls the AEDisposeToken function. If your application does not provide a token disposal function, the Apple Event Manager calls AEDisposeDesc instead.
Your token disposal function must be able to dispose of all of the token types used by your application.
If your application supports marking, a call to MyDisposeToken to dispose of a mark token lets you know that your can unmark the objects marked with that mark token.
RESULT CODES
noErr 0 No error occurred.
errAEEventNotHandled –1708 The token disposal function is unable to
dispose of the token; if the Apple Event
Manager gets this result from an
application’s token disposal routine, it looks
for a system token disposal function if one is
available; if this also fails, it calls the
AEDisposeDesc function to dispose of the
token
2MyGetErrorDesc
If you want to find out which descriptor record is responsible for an error that occurs during a call to the AEResolve function, you can provide an error callback function. An error callback function returns a pointer to an address at which the Apple Event Manager can store the descriptor record it is currently working with if an error occurs during a call to AEResolve.
FUNCTION MyGetErrorDesc (VAR errDescPtr: DescPtr): OSErr;
errDescPtr A pointer to an address.
DESCRIPTION
Shortly after your application calls AEResolve, the Apple Event Manager calls the MyGetErrorDesc function and writes a null descriptor record to the address returned. If an error occurs during the resolution of the object specifier record, the Apple Event Manager calls the MyGetError function again and writes the descriptor record—often an object specifier record—to the address returned.
Normally you should maintain a single global variable of type AEDesc whose address your MyGetErrorDesc function returns no matter how many times it is called. Be careful if you use any other method. When recovering from an error, the Apple Event Manager never writes to the address you provide unless it already contains a null descriptor record. Thus, if you don’t maintain a single global variable as just described, you should write null descriptor records to any addresses passed by your MyGetErrorDesc function that are different from the address returned the first time your function was called after a given call to AEResolve.
If the result code returned by the MyGetErrorDesc function has a nonzero value, the Apple Event Manager continues to resolve the object specifier record as if it had never called the error callback function.
RESULT CODES
noErr 0 No error occurred
2MyGetMarkToken
If your application supports marking, you must provide one mark token function. A mark token function returns a mark token.
FUNCTION MyGetMarkToken (containerToken: AEDesc;
containerClass: DescType;
VAR result: AEDesc): OSErr;
containerToken
The Apple event object that contains the elements to be marked with the mark token.
containerClass
The object class of the container that contains the objects to be marked.
result The mark token returned by MyGetMarkToken.
DESCRIPTION
The Apple Event Manager calls the MyGetMarkToken function provided by your application in order to get a mark token. Like other tokens, the mark token returned can be a descriptor record of any type; however, unlike other tokens, a mark token identifies the way your application will mark Apple event objects during the current session while resolving a single object specifier record that specifies the key form formTest.
A mark token is valid until the Apple Event Manager either disposes of it (by calling AEDisposeToken) or returns it as the result of the AEResolve function. If the final result of a call to AEResolve is a mark token, the Apple event objects currently marked for that mark token are those specified by the object specifier record passed to AEResolve, and your application can proceed to do whatever the Apple event has requested. Note that your application is responsible for disposing of a final mark token with a call to AEDisposeToken, just as for any other final token.
If your application supports marking, it should also provide a token disposal function modeled after the MyDisposeToken function described on page 2-260. When the Apple Event Manager calls AEDisposeToken to dispose of a mark token that is not the final result of a call to AEResolve, the subsequent call to your token disposal function lets you know that you can unmark the Apple event objects marked with that mark token. A call to AEDisposeDesc to dispose of a mark token (which would occur if you did not provide a token disposal function) would go unnoticed.
RESULT CODES
noErr 0 No error occurred.
errAEEventNotHandled –1708 The MyGetMarkToken function is unable to
return a mark token; if the Apple Event
Manager gets this result, it attempts to get a
mark token by calling the equivalent system
marking callback function.
SEE ALSO
For more information, see “Writing Marking Callback Functions,” which begins on page 2-179.
2MyMark
If your application supports marking, you must provide one object-marking function. An object-marking function marks a specific Apple event object.
FUNCTION MyMark (theToken: AEDesc; markToken: AEDesc;
markCount: LongInt): OSErr;
theToken The token for the Apple event object to be marked.
markToken The mark token used to mark the Apple event object.
markCount The number of times MyMark has been called for the current mark token (that is, the number of Apple event objects that have so far passed the test, including the element to be marked).
DESCRIPTION
The Apple Event Manager calls the MyMark function provided by your application in order to mark an Apple event object using the current mark token. In addition to marking the specified Apple event object, your MyMark function should record the mark count for each object that it marks. The mark count recorded for each marked Apple event object allows your application to distinguish one set of marked objects from another when a single object specifier record specifies more than one test, as described in the next section for the MyAdjustMarks function.
RESULT CODES
noErr 0 No error occurred.
errAEEventNotHandled –1708 The MyMark function is unable to mark the
specified Apple event object; if the Apple
Event Manager gets this result, it attempts to
mark the object by calling the equivalent
system object-marking function.
SEE ALSO
For more information, see “Writing Marking Callback Functions,” which begins on page 2-179.
2MyAdjustMarks
If your application supports marking, you must provide one mark-adjusting function. A mark-adjusting function adjusts the marks made with the current mark token.
FUNCTION MyAdjustMarks (newStart, newStop: LongInt;
markToken: AEDesc): OSErr;
newStart The mark count value (provided when the MyMark callback routine was called to mark the object) for the first object in the new set of marked objects.
newStop The mark count value (provided when the MyMark callback routine was called to mark the object) for the last object in the new set of marked objects.
markToken The mark token for the marked objects.
DESCRIPTION
When the Apple Event Manager needs to identify either a range of elements or the absolute position of an element in a group of Apple event objects that pass a test, it can use your applications’ mark-adjusting function to unmark objects that it has previously marked with your marking function. For example, if an object specifier record specifies “any row in the table ‘My Customers’ for which the City column is ‘San Francisco’,” the Apple Event Manager first uses the appropriate object accessor function to locate all the rows in the table for which the City column is “San Francisco,” and calls the application’s marking function repeatedly to mark them; it then generates a random number between 1 and the number of rows it found that passed the test, and calls the application’s mark-adjusting function to unmark all the rows whose mark count does not match the randomly generated number. If the randomly chosen row has a mark count value of 5, the Apple Event Manager passes “5” to the mark-adjusting function in both the newStart parameter and the newStop parameter, and passes the current mark token in the markToken parameter.
When your application calls your AdjustMyMarks function, your application must dispose of any data structures that it may have created in order to mark the previously marked objects.
RESULT CODES
noErr 0 No error occurred.
errAEEventNotHandled –1708 The MyAdjustMarks function is unable to
adjust the marks as requested; if the Apple
Event Manager gets this result, it attempts to
adjust the marks by calling the equivalent
system mark-adjusting function.
Summary of the Apple Event Manager
Constants
CONST gestaltAppleEventsAttr = 'evnt'; {selector for Apple events}
gestaltAppleEventsPresent = 0; {if this bit is set, then }
{ Apple Event Manager is }
{ available}
{Apple event descriptor types}
typeBoolean = 'bool'; {1-byte Boolean value}
typeChar = 'TEXT'; {unterminated string}
typeSMInt = 'shor'; {16-bit integer}
typeInteger = 'long'; {32-bit integer}
typeSMFloat = 'sing'; {SANE single}
typeFloat = 'doub'; {SANE double}
typeLongInteger = 'long'; {32-bit integer}
typeShortInteger = 'shor'; {16-bit integer}
typeLongFloat = 'doub'; {SANE double}
typeShortFloat = 'sing'; {SANE single}
typeExtended = 'exte'; {SANE extended}
typeComp = 'comp'; {SANE comp}
typeMagnitude = 'magn'; {unsigned 32-bit integer}
typeAEList = 'list'; {list of descriptor records}
typeAERecord = 'reco'; {list of keyword-specified }